angular.module('HTRD_AutoConsole.A').controller('LoginCtrl', ['$scope', '$state', '$window', 'LoginServ', 'DialogServ'
, function($scope, $state, $window, LoginServ, DialogServ) {
     var strapModal;

     // focus 和 blur方法
    //  var userfocus = function () {
    //       // 使用属性 控制 ng-class 的样式
    //       $scope.changeCheckoutConfig.userNameFocus = true;
    //       $scope.changeIcon.userNameIcon = true
    //  };
    //
    //  var userblur = function () {
    //       $scope.changeCheckoutConfig.userNameFocus = false;
    //       $scope.changeIcon.userNameIcon = false
    //  };
    //
    //  var pswfocus = function () {
    //       $scope.changeCheckoutConfig.passWordFocus = true;
    //       $scope.changeIcon.passWordIcon = true
    //  };
    //
    //  var pswblur = function () {
    //       $scope.changeCheckoutConfig.passWordFocus = false;
    //       $scope.changeIcon.passWordIcon = false
    //  };

     //登录按钮的点击事件
     var checkUserLoginFrom = function () {
        if(!!!$scope.userName){
          $scope.pswErr = $scope.pswNull = false;
          $scope.userNull = true;
          return;
        };

        if(!!!$scope.passWord){
          $scope.pswErr = $scope.userNull = false;
          $scope.pswNull = true;
          return;
        };

        var config = {
             userName : $scope.userName,
             passWord : $scope.passWord
        };

        if(!!$scope.reg.test(config.passWord) && !!$scope.userName){
             LoginServ.checkUserLoginFrom(config)
               .then(function(result){
                    if(result.stasus !== "200"){
                         alert("验证失败")
                    }else{
                    	alert("登录成功")
                         $state.go('console.base.home.index');
                    }
                    var token = result.token;
                    $window.localStorage.setItem('token',token);

               })
        }else{
          $scope.userNull = $scope.pswNull = false;
          $scope.pswErr = true;
        }
     };

     var parseDOM = function() {

     };

     var bindListener = function() {
        $scope.checkUserLoginFrom = checkUserLoginFrom;
        // $scope.userfocus = userfocus;
        // $scope.userblur = userblur;
        // $scope.pswfocus = pswfocus;
        // $scope.pswblur = pswblur;

     };

     var initPlugins = function() {
        $scope.pswErr = false;
        $scope.userNull = false;
        $scope.pswpswNull= false;
        var height = document.documentElement.clientHeight ;
        $('body').height(height);

        // 保存登录表单选中状态
        $scope.changeCheckoutConfig = { };

        // 保存icon图标选中状态
        $scope.changeIcon = { };

        // 初始化密码正则
        $scope.reg = /^(?![\d]+$)(?![a-zA-Z]+$)(?![!#$%^&*]+$)[\da-zA-Z_@/./+/-/_]{6,20}$/;
     };

     var init = function() {
          parseDOM();
          bindListener();
          initPlugins();
     };

     init();

}]);

angular.module('HTRD_AutoConsole.A').controller('BodyCtrl', ['$scope', '$state', '$window', '$timeout', function($scope, $state, $window,$timeout) {

  var parseDOM = function() {

  };

  var bindListener = function() {

  };

  var initPlugins = function() {
    
  };

  var init = function() {
    parseDOM();
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A')
.controller('HeaderCtrl', ['$scope', '$state', '$window','MessagePanelServ','NotificationServ','SocketServ', 'DialogServ','$timeout',
  function($scope, $state,$window,MessagePanelServ,NotificationServ,SocketServ,DialogServ,$timeout) {

  //消息中心
    var getMessage = function(){
      MessagePanelServ.getManagerInfo()
      .then(function (data) {

          if(data.status === 200){

              $scope.messageData =  data.results;
              $scope.messageCount = $scope.messageData.length;

              // 消息count显示与隐藏
              if ($scope.messageCount === 0) {
                $scope.isShowMessageCount = false;
              } else if($scope.messageCount > 99){
                $scope.messageCount = 99+"+";
              }

              // 數量
              $scope.$broadcast("messageCount", {
                messageCount: $scope.messageCount
              });

          };
      });
  };

    /*點擊查看、忽略及messagePanelState隱藏*/
	  $scope.$on("countReduce", function (evt,data) {

              MessagePanelServ.getManagerOperation(data)
              .then(function(result){
                if(result.status === 200){
                  $scope.messageCount = data.messageCount;

                    if ($scope.messageCount === 0) {
                      $scope.isShowMessageCount = false;
                      $scope.messagePanelState = false;
                    }
                  }

              })
	   });


    //点击图标让其弹出框显示与隐藏
    var toggleMessagePanel = function() {
      getMessage();
    // 消息count显示与隐藏
        if($scope.messageCount == 0){
          return false;
        }else {
          $scope.messagePanelState = !!!$scope.messagePanelState;
        }
  };

  //点击关闭按钮,弹框
    var toggleQuitLogin = function () {
      strapModal = DialogServ.modal({
        'scope': $scope,
        'templateUrl': 'view/console/modal/quitLogin.html'
      });
      strapModal.$promise.then(strapModal.show);
    };

    //弹出框的确定按钮
    var quitConfirm = function () {
      strapModal.hide();
      $state.go('login');
    };

    var bindListener = function() {
      $scope.toggleMessagePanel = toggleMessagePanel;
      $scope.toggleQuitLogin = toggleQuitLogin;
      $scope.quitConfirm = quitConfirm
    };

    var initPlugins = function() {
      $scope.messagePanelState = false;
      $scope.isShowMessageCount = true;

      $scope.$on("clearMsg",function (evt,data) {

        MessagePanelServ.getManagerClean()
          .then(function(result){
            if(result.status === 200){
              $scope.isShowMessageCount = false;
              $scope.messagePanelState = data.messagePanelState;
              $scope.messageCount= data.messageCount;

              //列表清空
              $scope.messageData = data.messageData;
            }
          })
      });

      $scope.$on("toQuit",function (evt,data) {
        $scope.quitLoginState = data.quitLoginState;
      })
    };

    var callback = function(data){
      console.log('callback'+"---"+data);
      $state.go("console.base.manager.process",{id: data.pipeline})
    };

    //浏览器消息通知
    SocketServ.initSocket(0);

    SocketServ.onMessage(function (data) {

      if(data){
          $scope.isShowMessageCount = true;
          $scope.messageCount += 1;
      };

      NotificationServ.init(data,callback);

    });

    var init = function() {
      bindListener();
      initPlugins();
      getMessage();
    };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('LeftCtrl', ['$scope', '$state', '$window','$timeout', function($scope, $state, $window,$timeout) {


  var menuList = [
    {
      title: '首页',
      url: '',
      icon: 'icon-system',
      childItems: [
        {
          title: '系统首页',
          url: 'console.base.home.index',
          icon: 'icon-system-index'
        }
      ]
    },
    {
      title: '流程管理',
      url: '',
      icon: 'icon-manager',
      childItems: [
        {
          title: '流程列表',
          url: 'console.base.manager.list',
          icon: 'icon-process'
        },

        {
          title: '流程结果查询',
          url: 'console.base.manager.result',
          icon: 'icon-result'
        },
        {
          title: '告警查询',
          url: 'console.base.manager.warn',
          icon: 'icon-warn'
        }
      ]
    },
    {
      title: '流程模板',
      url: '',
      icon: 'icon-template',
      childItems: [
        {
          title: '流程模板',
          url: 'console.base.template',
          icon: 'icon-template-index'
        }
      ]
    },
    // {
    //   title: '操作日志',
    //   url: '',
    //   icon: 'icon-log',
    //   childItems: [
    //     {
    //       title: '操作日志',
    //       url: 'console.base.log',
    //       icon: 'icon-log-index'
    //     }
    //   ]
    // },

    {
      title: '流程调度',
      url: '',
      icon: 'icon-control',
      childItems: [
        {
          title: '流程调度',
          url: 'console.base.manager.controlList',
          icon: 'icon-control-index'
        }
      ]
    },
    {
      title: '假日方案',
      url: '',
      icon: 'icon-holiday',
      childItems: [
        {
          title: '假日方案',
          url: 'console.base.manager.holidayList',
          icon: 'icon-holiday-index'
        }
      ]
    }
  ];

  var routerChange = function(item) {

    if (!!item.url) {
      $state.go(item.url);
    };
  };

  var parseDOM = function() {

  };

  var bindListener = function() {
    $scope.routerChange = routerChange;
  };

  var initPlugins = function() {
    $scope.menuList = menuList;

    // $timeout(function () {
      var documentHeight = $(document).height();
      $(".page-sidebar").css("height",documentHeight);
    // }, 100);
    // onresize
  };

  var init = function() {
    parseDOM();
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('HomeCtrl', ['$scope', '$state', '$window', 'HomeServ',function($scope, $state, $window,HomeServ) {
  console.log('HomeCtrl');

      var homeConfig = {
            limit: 5
      };

      var bindListener = function() {

      };

      var initPlugins = function() {

            $scope.homeConfig = homeConfig;

            $scope.waitRun = {
              count : 0
            }

            // 今日待执行
           /* HomeServ.getWaitRun()
            .then(function(result) {
            if (result.status === 200) {
                    $scope.waitRun = result.results
                  };
            });*/


            //执行中
            HomeServ.getRuning(homeConfig)
              .then(function(result) {
                if(result.status === 200){
                  $scope.runing = result.results;
                }
              });

            //执行告警
            HomeServ.getWarnRun(homeConfig)
              .then(function(result) {
                if(result.status === 200){
                  $scope.warnRun = result.results
                }
              });


            //已结束
            HomeServ.getEndRun(homeConfig)
            .then(function(result) {
              if(result.status === 200){
                $scope.endRun = result.results;
              }
            });

            //执行成功
            HomeServ.getSuccessRun(homeConfig)
            .then(function(result) {
              if(result.status === 200){
                $scope.successRun = result.results;
              }
            });

            //手工接管
            HomeServ.getHandOver(homeConfig)
            .then(function(result) {
              if (result.status === 200) {
                $scope.handOver = result.results;
              }
            });
        };

      var init = function() {
        bindListener();
        initPlugins()
      };

      init();
}]);

/**
 * Created by Administrator on 2017/4/13.
 */

angular.module('HTRD_AutoConsole.A')
	.controller('HomeEndCtrl', ['$scope', '$state', '$window','HomeServ','StatusMapServ','DateParseServ','$timeout',function($scope, $state, $window,HomeServ,StatusMapServ,DateParseServ,$timeout) {
		console.log('HomeEndCtrl');
		//面包屑
	    var breadcrumbsData = [
		      {
		        'iconClass': 'icon-home',
		        'text': '首页',
		        'link': 'console.base.home.index'
		      },
		      {
		        'text': '已结束'
		      }
	    	];

		var homeEndListConfig = {
			page: 1,
			limit: 20
		};

		var toManagerProcess = function (item) {
			$state.go('console.base.manager.historyProcess',{
				id: item.id,
				processId: item.pipeline
			});
		};

		var getHomeEndList;
		//已结束的排序
		$scope.endList = {};
		$scope.endList.endTimeSort = "sorting_desc";
		var changeHomeEndStartTimeSort = function (endList) {

			//清除其他header样式
			$scope.endList.endTimeSort = "";
			$scope.endList.processSort = "";
			$scope.endList.nodeSort = "";
			$scope.endList.executorSort = "";
			$scope.endList.terminatorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.endList.startTimeSort){

				$scope.endList.startTimeSort = "sorting_asc";
				//配置传参升序排列
				$scope.homeEndListConfig.sort = "started_at";
				getHomeEndList()

			}else if($scope.endList.startTimeSort === 'sorting_asc'){

				$scope.endList.startTimeSort = "sorting_desc";
				$scope.homeEndListConfig.sort = "-started_at";
				getHomeEndList()

			}else if($scope.endList.startTimeSort === 'sorting_desc'){

				$scope.endList.startTimeSort = "sorting_asc";

				$scope.homeEndListConfig.sort = "started_at";
				getHomeEndList()

			}
		};
		var changeHomeEndEndTimeSort = function (endList) {

			//清除其他header样式
			$scope.endList.startTimeSort = "";
			$scope.endList.processSort = "";
			$scope.endList.nodeSort = "";
			$scope.endList.executorSort = "";
			$scope.endList.terminatorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.endList.endTimeSort){
				$scope.endList.endTimeSort = "sorting_asc" ;
				$scope.homeEndListConfig.sort = "started_at";
				getHomeEndList()
			}else if($scope.endList.endTimeSort === 'sorting_asc'){
				$scope.endList.endTimeSort = "sorting_desc";
				$scope.homeEndListConfig.sort = "-started_at";
				getHomeEndList()
			}else if($scope.endList.endTimeSort === 'sorting_desc'){
				$scope.endList.endTimeSort= "sorting_asc";
				$scope.homeEndListConfig.sort = "started_at";
				getHomeEndList()
			}
		};
		var changeHomeEndProcessSort = function (endList) {

			//清除其他header样式
			$scope.endList.startTimeSort = "";
			$scope.endList.endTimeSort = "";
			$scope.endList.nodeSort = "";
			$scope.endList.executorSort = "";
			$scope.endList.terminatorSort = "";

			if(!!!$scope.endList.processSort){
				$scope.endList.processSort = "sorting_asc" ;
				$scope.homeEndListConfig.sort = "id";
				getHomeEndList()
			}else if($scope.endList.processSort === 'sorting_asc'){
				$scope.endList.processSort = "sorting_desc";
				$scope.homeEndListConfig.sort = "-id";
				getHomeEndList()
			}else if($scope.endList.processSort === 'sorting_desc'){
				$scope.endList.processSort = "sorting_asc";
				$scope.homeEndListConfig.sort = "id";
				getHomeEndList()
			}
		};
		var changeHomeEndNodeSort = function (endList) {
			//清除其他header样式
			$scope.endList.startTimeSort = "";
			$scope.endList.endTimeSort = "";
			$scope.endList.processSort = "";
			$scope.endList.executorSort = "";
			$scope.endList.terminatorSort = "";

			if(!!!$scope.endList.nodeSort){
				$scope.endList.nodeSort = "sorting_asc" ;
				$scope.homeEndListConfig.sort = "id";
				getHomeEndList()
			}else if($scope.endList.nodeSort === 'sorting_asc'){
				$scope.endList.nodeSort = "sorting_desc";
				$scope.homeEndListConfig.sort = "-id";
				getHomeEndList()
			}else if($scope.endList.nodeSort === 'sorting_desc'){
				$scope.endList.nodeSort = "sorting_asc";
				$scope.homeEndListConfig.sort = "id";
				getHomeEndList()
			}
		};
		var changeHomeEndExecutorSort = function (endList) {
			//清除其他header样式
			$scope.endList.startTimeSort = "";
			$scope.endList.endTimeSort = "";
			$scope.endList.processSort = "";
			$scope.endList.nodeSort = "";
			$scope.endList.terminatorSort = "";

			if(!!!$scope.endList.executorSort){
				$scope.endList.executorSort = "sorting_asc" ;
				$scope.homeEndListConfig.sort = "id";
				getHomeEndList()
			}else if($scope.endList.executorSort === 'sorting_asc'){
				$scope.endList.executorSort = "sorting_desc";
				$scope.homeEndListConfig.sort = "-id";
				getHomeEndList()
			}else if($scope.endList.executorSort === 'sorting_desc'){
				$scope.endList.executorSort = "sorting_asc";
				$scope.homeEndListConfig.sort = "id";
				getHomeEndList()
			}
		};

		var bindListener = function() {

			$scope.changeHomeEndStartTimeSort = changeHomeEndStartTimeSort;
			$scope.changeHomeEndEndTimeSort = changeHomeEndEndTimeSort;
			//$scope.changeHomeEndProcessSort = changeHomeEndProcessSort;
			//$scope.changeHomeEndNodeSort = changeHomeEndNodeSort;
			//$scope.changeHomeEndExecutorSort = changeHomeEndExecutorSort;

			$scope.toManagerProcess = toManagerProcess;
		};

		var initPlugins = function() {

			$scope.breadcrumbsData = breadcrumbsData;

			//执行(分页)的配置
			$scope.homeEndListConfig = homeEndListConfig;
			//已结束
			getHomeEndList = function () {
				HomeServ.getEndRun(homeEndListConfig)
					.then(function(data) {
						if(data.status === 200){
							$scope.endRun = data;
							$scope.endRun.result = $scope.endRun.results.data;
							$scope.endRun.result.map(function(item){
								var started_at = DateParseServ.dateParse(item.started_at);
								var ended_at = DateParseServ.dateParse(item.ended_at)
								var model = StatusMapServ.getStatusData(item.result_status);
								item.result_status = model.text.substring(0,4);
								item.started_at = started_at;
								item.ended_at = ended_at;
							})
							$scope.$broadcast("toList",{
								endRun: data.results.data,
								count: data.results.count,
								limit:  $scope.homeEndListConfig.limit,
								page: $scope.homeEndListConfig.page || data.results.page
							})
						}
					});
			};
			$timeout(function () {
				getHomeEndList()
			},1000);
				$scope.$on('toPage',function (evt,data) {
				$scope.homeEndListConfig.page = data.page;
				getHomeEndList()
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);

/**
 * Created by Administrator on 2017/4/13.
 */
angular.module('HTRD_AutoConsole.A')
	.controller('HomeHandListCtrl', ['$scope', '$state', '$window','HomeServ','StatusMapServ','DateParseServ','$timeout',function($scope, $state, $window,HomeServ,StatusMapServ,DateParseServ,$timeout) {
		console.log('HomeHandListCtrl');

		//面包屑
	    	var breadcrumbsData = [
		      {
		        'iconClass': 'icon-home',
		        'text': '首页',
		        'link': 'console.base.home.index'
		      },
		      {
		        'text': '手工接管'
		      }
	    	];

		var homeHandListConfig = {
			limit: 20,
			page: 1
		};

		var toManagerProcess = function (item) {
			$state.go('console.base.manager.historyProcess',{
				id: item.id,
				processId: item.pipeline
			});
		};

		var getHomeHandList;
		//手工接管的排序
		$scope.handList = {};
		$scope.handList.endTimeSort = "sorting_desc";
		var changeHomeHandStartTimeSort = function (handList) {

			//清除其他header样式
			$scope.handList.endTimeSort = "";
			$scope.handList.processSort = "";
			$scope.handList.nodeSort = "";
			$scope.handList.executorSort = "";
			$scope.handList.terminatorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.handList.startTimeSort){
				$scope.handList.startTimeSort = "sorting_asc";

				//配置传参升序排列
				$scope.homeHandListConfig.sort = "started_at";
				getHomeHandList()

			}else if($scope.handList.startTimeSort === 'sorting_asc'){

				$scope.handList.startTimeSort = "sorting_desc";
				$scope.homeHandListConfig.sort = "-started_at";
				getHomeHandList()

			}else if($scope.handList.startTimeSort === 'sorting_desc'){

				$scope.handList.startTimeSort = "sorting_asc";
				$scope.homeHandListConfig.sort = "started_at";
				getHomeHandList()

			}
		};
		var changeHomeHandEndTimeSort = function (handList) {

			$scope.handList.startTimeSort = "";
			$scope.handList.processSort = "";
			$scope.handList.nodeSort = "";
			$scope.handList.executorSort = "";
			$scope.handList.terminatorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.handList.endTimeSort){
				$scope.handList.endTimeSort = "sorting_asc" ;
				$scope.homeHandListConfig.sort = "ended_at";
				getHomeHandList()
			}else if($scope.handList.endTimeSort === 'sorting_asc'){
				$scope.handList.endTimeSort = "sorting_desc";
				$scope.homeHandListConfig.sort = "-ended_at";
				getHomeHandList()
			}else if($scope.handList.endTimeSort === 'sorting_desc'){
				$scope.handList.endTimeSort= "sorting_asc";
				$scope.homeHandListConfig.sort = "ended_at";
				getHomeHandList()
			}
		};
		var changeHomeHandProcessSort = function (handList) {

			//清除其他header样式
			$scope.handList.startTimeSort = "";
			$scope.handList.endTimeSort = "";
			$scope.handList.nodeSort = "";
			$scope.handList.executorSort = "";
			$scope.handList.terminatorSort = "";

			if(!!!$scope.handList.processSort){
				$scope.handList.processSort = "sorting_asc" ;
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}else if($scope.handList.processSort === 'sorting_asc'){
				$scope.handList.processSort = "sorting_desc";
				$scope.homeHandListConfig.sort = "-id";
				getHomeHandList()
			}else if($scope.handList.processSort === 'sorting_desc'){
				$scope.handList.processSort = "sorting_asc";
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}
		};
		var changeHomeHandNodeSort = function (handList) {
			//清除其他header样式
			$scope.handList.startTimeSort = "";
			$scope.handList.endTimeSort = "";
			$scope.handList.processSort = "";
			$scope.handList.executorSort = "";
			$scope.handList.terminatorSort = "";

			if(!!!$scope.handList.nodeSort){
				$scope.handList.nodeSort = "sorting_asc" ;
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}else if($scope.handList.nodeSort === 'sorting_asc'){
				$scope.handList.nodeSort = "sorting_desc";
				$scope.homeHandListConfig.sort = "-id";
				getHomeHandList()
			}else if($scope.handList.nodeSort === 'sorting_desc'){
				$scope.handList.nodeSort = "sorting_asc";
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}
		};
		var changeHomeHandExecutorSort = function (handList) {

			$scope.handList.startTimeSort = "";
			$scope.handList.endTimeSort = "";
			$scope.handList.processSort = "";
			$scope.handList.nodeSort = "";
			$scope.handList.terminatorSort = "";

			if(!!!$scope.handList.executorSort){
				$scope.handList.executorSort = "sorting_asc" ;
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}else if($scope.handList.executorSort === 'sorting_asc'){
				$scope.handList.executorSort = "sorting_desc";
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}else if($scope.handList.executorSort === 'sorting_desc'){
				$scope.handList.executorSort = "sorting_asc";
				$scope.homeHandListConfig.sort = "id";
				getHomeHandList()
			}
		};

		var bindListener = function() {

			$scope.changeHomeHandStartTimeSort = changeHomeHandStartTimeSort;
			$scope.changeHomeHandEndTimeSort = changeHomeHandEndTimeSort;
			//$scope.changeHomeHandProcessSort = changeHomeHandProcessSort;
			//$scope.changeHomeHandNodeSort = changeHomeHandNodeSort;
			//$scope.changeHomeHandExecutorSort = changeHomeHandExecutorSort;

			$scope.toManagerProcess = toManagerProcess
		};

		var initPlugins = function() {
			$scope.breadcrumbsData = breadcrumbsData;
			//执行(分页)的配置
			$scope.homeHandListConfig = homeHandListConfig;

			getHomeHandList = function () {
				HomeServ.getHandOver(homeHandListConfig)
					.then(function(data) {
						if(data.status === 200){
							$scope.handOver = data;
							$scope.handOver.result = $scope.handOver.results.data;
							$scope.handOver.result.map(function(item){

								var started_at = DateParseServ.dateParse(item.started_at);
								var ended_at = DateParseServ.dateParse(item.ended_at)
								var model = StatusMapServ.getStatusData(item.result_status);
								item.result_status = model.text;
								item.started_at = started_at;
								item.ended_at = ended_at;

							})
							$scope.$broadcast("toList",{
								handOver: data.results.data,
								count: data.results.count,
								limit:  $scope.homeHandListConfig.limit,
								page: $scope.homeHandListConfig.page || data.results.page
							});
						}
					});
			};
			$timeout(function () {
				getHomeHandList()
			},1000);
			$scope.$on('toPage',function (evt,data) {
				$scope.homeHandListConfig.page = data.page;
				getHomeHandList()
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);

/**
 * Created by Administrator on 2017/4/12.
 */
angular.module('HTRD_AutoConsole.A')
	.controller('HomeRunListCtrl', ['$scope', '$state', '$window','HomeServ','StatusMapServ','DateParseServ','$timeout',function($scope, $state, $window,HomeServ,StatusMapServ,DateParseServ,$timeout) {
		console.log('HomeRunListCtrl');

		//面包屑
	    	var breadcrumbsData = [
		      {
		        'iconClass': 'icon-home',
		        'text': '首页',
		        'link': 'console.base.home.index'
		      },
		      {
		        'text': '执行中'
		      }
	    	];

		var homeRunListConfig = {
			page: 1,
			limit: 20
		};
		
		var toManagerProcess = function (item) {
			$state.go("console.base.manager.process",{id: item.pipeline});
		};

		var getHomeRuningList;
		//执行中的排序
		$scope.runingList = {};
		$scope.runingList.timeSort = "sorting_desc";
		var changeHomeRuningProcessSort = function (runingList) {

			//清除其他header样式
			$scope.runingList.nodeSort = "";
			$scope.runingList.createrSort = "";
			$scope.runingList.modifierSort = "";
			$scope.runingList.auditorSort = "";
			$scope.runingList.timeSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.runingList.processSort){
				$scope.runingList.processSort = "sorting_asc";

				//配置传参升序排列
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()

			}else if($scope.runingList.processSort === 'sorting_asc'){

				$scope.runingList.processSort = "sorting_desc";
				$scope.homeRunListConfig.sort = "-id";
				getHomeRuningList()

			}else if($scope.runingList.processSort === 'sorting_desc'){

				$scope.runingList.processSort = "sorting_asc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()

			}
		};
		var changeHomeRuningNodeSort = function (runingList) {

			$scope.runingList.processSort = "";
			$scope.runingList.createrSort = "";
			$scope.runingList.modifierSort = "";
			$scope.runingList.auditorSort = "";
			$scope.runingList.timeSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.runingList.nodeSort){
				$scope.runingList.nodeSort = "sorting_asc" ;
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}else if($scope.runingList.nodeSort === 'sorting_asc'){
				$scope.runingList.nodeSort = "sorting_desc";
				$scope.homeRunListConfig.sort = "-id";
				getHomeRuningList()
			}else if($scope.runingList.nodeSort === 'sorting_desc'){
				$scope.runingList.nodeSort = "sorting_asc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}
		};
		var changeHomeRuningCreaterSort = function (runingList) {

			//清除其他header样式
			$scope.runingList.processSort = "";
			$scope.runingList.nodeSort = "";
			$scope.runingList.modifierSort = "";
			$scope.runingList.auditorSort = "";
			$scope.runingList.timeSort = "";

			if(!!!$scope.runingList.createrSort){
				$scope.runingList.createrSort = "sorting_asc" ;
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList(homeRunListConfig)
			}else if($scope.runingList.createrSort === 'sorting_asc'){
				$scope.runingList.createrSort = "sorting_desc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList(homeRunListConfig)
			}else if($scope.runingList.createrSort === 'sorting_desc'){
				$scope.runingList.createrSort = "sorting_asc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}
		};
		var changeHomeRuningModifierSort = function (runingList) {

			$scope.runingList.processSort = "";
			$scope.runingList.nodeSort = "";
			$scope.runingList.createrSort = "";
			$scope.runingList.auditorSort = "";
			$scope.runingList.timeSort = "";

			if(!!!$scope.runingList.modifierSort){
				$scope.runingList.modifierSort = "sorting_asc" ;
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}else if($scope.runingList.modifierSort === 'sorting_asc'){
				$scope.runingList.modifierSort = "sorting_desc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}else if($scope.runingList.modifierSort === 'sorting_desc'){
				$scope.runingList.modifierSort = "sorting_asc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}
		};
		var changeHomeRuningAuditorSort = function (runingList) {
			//清除其他header样式
			$scope.runingList.processSort = "";
			$scope.runingList.nodeSort = "";
			$scope.runingList.createrSort = "";
			$scope.runingList.modifierSort = "";
			$scope.runingList.timeSort = "";

			if(!!!$scope.runingList.auditorSort){
				$scope.runingList.auditorSort = "sorting_asc" ;
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}else if($scope.runingList.auditorSort === 'sorting_asc'){
				$scope.runingList.auditorSort = "sorting_desc";
				$scope.homeRunListConfig.sort = "-id";
				getHomeRuningList()
			}else if($scope.runingList.auditorSort === 'sorting_desc'){
				$scope.runingList.auditorSort = "sorting_asc";
				$scope.homeRunListConfig.sort = "id";
				getHomeRuningList()
			}
		};
		var changeHomeRuningTimeSort = function (runingList) {
			//清除其他header样式
			$scope.runingList.processSort = "";
			$scope.runingList.nodeSort = "";
			$scope.runingList.createrSort = "";
			$scope.runingList.modifierSort = "";
			$scope.runingList.auditorSort = "";

			if(!!!$scope.runingList.timeSort){
				$scope.runingList.timeSort = "sorting_asc" ;
				$scope.homeRunListConfig.sort = "started_at";
				getHomeRuningList()
			}else if($scope.runingList.timeSort === 'sorting_asc'){
				$scope.runingList.timeSort = "sorting_desc";
				$scope.homeRunListConfig.sort = "-started_at";
				getHomeRuningList()
			}else if($scope.runingList.timeSort === 'sorting_desc'){
				$scope.runingList.timeSort = "sorting_asc";
				$scope.homeRunListConfig.sort = "started_at";
				getHomeRuningList()
			}
		};

		var bindListener = function() {

			//$scope.changeHomeRuningProcessSort = changeHomeRuningProcessSort;
			//$scope.changeHomeRuningNodeSort = changeHomeRuningNodeSort;
			//$scope.changeHomeRuningCreaterSort = changeHomeRuningCreaterSort;
			//$scope.changeHomeRuningModifierSort = changeHomeRuningModifierSort;
			//$scope.changeHomeRuningAuditorSort = changeHomeRuningAuditorSort;
			$scope.changeHomeRuningTimeSort = changeHomeRuningTimeSort;

			$scope.toManagerProcess = toManagerProcess
		};

		var initPlugins = function() {
			$scope.breadcrumbsData = breadcrumbsData;
			//执行(分页)的配置
			$scope.homeRunListConfig = homeRunListConfig;

			///执行中
			getHomeRuningList = function () {
				console.log(homeRunListConfig)
				HomeServ.getRuning(homeRunListConfig)
					.then(function(data) {
						if(data.status === 200){
							$scope.runing = data;
							$scope.runing.result = $scope.runing.results.data;
							$scope.runing.result.map(function(item){
								var model = StatusMapServ.getStatusData(item.result_status);
								var started_at = DateParseServ.dateParse(item.started_at)
								item.result_status = model.text.substring(0,4);
								item.started_at = started_at;
							})
							$scope.$broadcast("toList",{
								runing: data.results.data,
								count: data.results.count,
								limit:  $scope.homeRunListConfig.limit,
								page: $scope.homeRunListConfig.page || data.results.page
							})
						}
					});
			};
			$timeout(function () {
				getHomeRuningList()
			},1000);
			$scope.$on('toPage',function (evt,data) {
				$scope.homeRunListConfig.page = data.page;
				getHomeRuningList()
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);

/**
 * Created by Administrator on 2017/4/12.
 */
angular.module('HTRD_AutoConsole.A')
	.controller('HomeSuccessListCtrl', ['$scope', '$state', '$window','HomeServ','StatusMapServ','DateParseServ','$timeout',function($scope, $state, $window,HomeServ,StatusMapServ,DateParseServ,$timeout) {
		console.log('HomeSuccessListCtrl');

		//面包屑
	    	var breadcrumbsData = [
		      {
		        'iconClass': 'icon-home',
		        'text': '首页',
		        'link': 'console.base.home.index'
		      },
		      {
		        'text': '执行成功'
		      }
	    	];

		var homeSuccessListConfig = {
			limit: 20,
			page: 1
		};

		var toManagerProcess = function (item) {
			$state.go('console.base.manager.historyProcess',{
				id: item.id,
				processId: item.pipeline
			});
		};

		var getSuccessList;
		//执行成功的排序
		$scope.successList = {};
		$scope.successList.endTimeSort = "sorting_desc";
		var changeHomesuccessListStartTimeSort = function (successList) {

			//清除其他header样式
			$scope.successList.endTimeSort = "";
			$scope.successList.processSort = "";
			$scope.successList.nodeSort = "";
			$scope.successList.executorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.successList.startTimeSort){
				$scope.successList.startTimeSort = "sorting_asc";
				$scope.homeSuccessListConfig.sort = "started_at";
				getSuccessList()

			}else if($scope.successList.startTimeSort === 'sorting_asc'){

				$scope.successList.startTimeSort = "sorting_desc";
				$scope.homeSuccessListConfig.sort = "-started_at";
				getSuccessList()

			}else if($scope.successList.startTimeSort === 'sorting_desc'){

				$scope.successList.startTimeSort = "sorting_asc";
				$scope.homeSuccessListConfig.sort = "started_at";
				getSuccessList()

			}
		};
		var changeHomesuccessListEndTimeSort = function (successList) {

			//清除其他header样式
			$scope.successList.startTimeSort = "";
			$scope.successList.processSort = "";
			$scope.successList.nodeSort = "";
			$scope.successList.executorSort = "";
			$scope.successList.terminatorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.successList.endTimeSort){
				$scope.successList.endTimeSort = "sorting_asc" ;
				$scope.homeSuccessListConfig.sort = "ended_at";
				getSuccessList()
			}else if($scope.successList.endTimeSort === 'sorting_asc'){
				$scope.successList.endTimeSort = "sorting_desc";
				$scope.homeSuccessListConfig.sort = "-ended_at";
				getSuccessList()
			}else if($scope.successList.endTimeSort === 'sorting_desc'){
				$scope.successList.endTimeSort= "sorting_asc";
				$scope.homeSuccessListConfig.sort = "ended_at";
				getSuccessList()
			}
		};
		var changeHomesuccessListProcessSort = function (successList) {

			//清除其他header样式
			$scope.successList.startTimeSort = "";
			$scope.successList.endTimeSort = "";
			$scope.successList.nodeSort = "";
			$scope.successList.executorSort = "";
			$scope.successList.terminatorSort = "";

			if(!!!$scope.successList.processSort){
				$scope.successList.processSort = "sorting_asc" ;
				$scope.homeSuccessListConfig.sort = "id";
				getSuccessList()
			}else if($scope.successList.processSort === 'sorting_asc'){
				$scope.successList.processSort = "sorting_desc";
				$scope.homeSuccessListConfig.sort = "-id";
				getSuccessList()
			}else if($scope.successList.processSort === 'sorting_desc'){
				$scope.successList.processSort = "sorting_asc";
				$scope.homeSuccessListConfig.sort = "id";
				getSuccessList()
			}
		};
		var changeHomesuccessListNodeSort = function (successList) {
			//清除其他header样式
			$scope.successList.startTimeSort = "";
			$scope.successList.endTimeSort = "";
			$scope.successList.processSort = "";
			$scope.successList.executorSort = "";
			$scope.successList.terminatorSort = "";

			if(!!!$scope.successList.nodeSort){
				$scope.successList.nodeSort = "sorting_asc" ;
				$scope.homeSuccessListConfig.sort = "id";
				getSuccessList()
			}else if($scope.successList.nodeSort === 'sorting_asc'){
				$scope.successList.nodeSort = "sorting_desc";
				$scope.homeSuccessListConfig.sort = "-id";
				getSuccessList()
			}else if($scope.successList.nodeSort === 'sorting_desc'){
				$scope.successList.nodeSort = "sorting_asc";
				$scope.homeSuccessListConfig.sort = "id";
				getSuccessList()
			}
		};
		var changeHomesuccessListExecutorSort = function (successList) {
			//清除其他header样式
			$scope.successList.startTimeSort = "";
			$scope.successList.endTimeSort = "";
			$scope.successList.processSort = "";
			$scope.successList.nodeSort = "";
			$scope.successList.terminatorSort = "";

			if(!!!$scope.successList.executorSort){
				$scope.successList.executorSort = "sorting_asc" ;
				$scope.homeSuccessListConfig.sort = "id";
				getSuccessList()
			}else if($scope.successList.executorSort === 'sorting_asc'){
				$scope.successList.executorSort = "sorting_desc";
				$scope.homeSuccessListConfig.sort = "-id";
				getSuccessList()
			}else if($scope.successList.executorSort === 'sorting_desc'){
				$scope.successList.executorSort = "sorting_asc";
				$scope.homeSuccessListConfig.sort = "id";
				getSuccessList()
			}
		};

		var bindListener = function() {

			$scope.changeHomesuccessListStartTimeSort = changeHomesuccessListStartTimeSort;
			$scope.changeHomesuccessListEndTimeSort = changeHomesuccessListEndTimeSort;
			//$scope.changeHomesuccessListProcessSort = changeHomesuccessListProcessSort;
			//$scope.changeHomesuccessListNodeSort = changeHomesuccessListNodeSort;
			//$scope.changeHomesuccessListExecutorSort = changeHomesuccessListExecutorSort;
			$scope.toManagerProcess = toManagerProcess
		};

		var initPlugins = function() {
			$scope.breadcrumbsData = breadcrumbsData;
			//执行(分页)的配置
			$scope.homeSuccessListConfig = homeSuccessListConfig;

			getSuccessList = function () {
				
				HomeServ.getSuccessRun(homeSuccessListConfig)
					.then(function(data) {
						if(data.status === 200){
							$scope.successRun = data;
							$scope.successRun.result = $scope.successRun.results.data;
							$scope.successRun.result.map(function(item){

								var started_at = DateParseServ.dateParse(item.started_at);
								var ended_at = DateParseServ.dateParse(item.ended_at)
								var model = StatusMapServ.getStatusData(item.result_status);
								item.started_at = started_at;
								item.ended_at = ended_at;
								item.result_status = model.text;
							})
							$scope.$broadcast("toList",{
								successRun: data.results.data,
								count: data.results.count,
								limit:  $scope.homeSuccessListConfig.limit,
								page: $scope.homeSuccessListConfig.page || data.results.page
							})
						}
					});
			};
			$timeout(function () {
				getSuccessList()
			},1000);
			$scope.$on('toPage',function (evt,data) {
				$scope.homeSuccessListConfig.page = data.page;
				getSuccessList()
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);

/**
 * Created by Administrator on 2017/4/12.
 */
angular.module('HTRD_AutoConsole.A')
	.controller('HomeWaitListCtrl', ['$scope', '$state', '$window','HomeServ','$timeout',function($scope, $state, $window,HomeServ,$timeout) {
		console.log('HomeWaitListCtrl');

		//初始化
		var getHomeWaitList;
		
		//今日待执行的排序
		//$scope.waitList = {};

		//今日执行获取更多数据的配置
		var homeWaitListConfig = {
			page: 1,
			limit: 20
		};

		var toManagerProcess = function (item) {
			$state.go("console.base.manager.process",{id: item.pipeline});
		};
		
		//$scope.waitList.processSort = "sorting_desc";
		/*var changeHomeWaitProcessSort = function (waitList) {

			//清除其他header样式
			$scope.waitList.nodeSort = "";
			$scope.waitList.createrSort = "";
			$scope.waitList.modifierSort = "";
			$scope.waitList.auditorSort = "";

			//默认为空 点击按top排序
			if(!!!$scope.waitList.processSort){

				$scope.waitList.processSort = "sorting_asc";
				//配置传参升序排列
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()

			}else if($scope.waitList.processSort === 'sorting_asc'){

				$scope.waitList.processSort = "sorting_desc";
				$scope.homeWaitListConfig.sort = "-id";
				getHomeWaitList()

			}else if($scope.waitList.processSort === 'sorting_desc'){

				$scope.waitList.processSort = "sorting_asc";
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}
		};
		var changeHomeWaitNodeSort = function (waitList) {

			$scope.waitList.processSort = "";
			$scope.waitList.createrSort = "";
			$scope.waitList.modifierSort = "";
			$scope.waitList.auditorSort = "";

			if(!!!$scope.waitList.nodeSort){
				//默认为空 点击按top排序
				$scope.waitList.nodeSort = "sorting_asc" ;
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}else if($scope.waitList.nodeSort === 'sorting_asc'){
				$scope.waitList.nodeSort = "sorting_desc";
				$scope.homeWaitListConfig.sort = "-id";
				getHomeWaitList()
			}else if($scope.waitList.nodeSort === 'sorting_desc'){
				$scope.waitList.nodeSort = "sorting_asc";
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}
		};
		var changeHomeWaitCreaterSort = function (waitList) {

			$scope.waitList.processSort = "";
			$scope.waitList.nodeSort = "";
			$scope.waitList.modifierSort = "";
			$scope.waitList.auditorSort = "";

			if(!!!$scope.waitList.createrSort){
				$scope.waitList.createrSort = "sorting_asc" ;
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}else if($scope.waitList.createrSort === 'sorting_asc'){
				$scope.waitList.createrSort = "sorting_desc";
				$scope.homeWaitListConfig.sort = "-id";
				getHomeWaitList()
			}else if($scope.waitList.createrSort === 'sorting_desc'){
				$scope.waitList.createrSort = "sorting_asc";
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}
		};
		var changeHomeWaitModifierSort = function (waitList) {

			$scope.waitList.processSort = "";
			$scope.waitList.nodeSort = "";
			$scope.waitList.createrSort = "";
			$scope.waitList.auditorSort = "";

			if(!!!$scope.waitList.modifierSort){
				$scope.waitList.modifierSort = "sorting_asc" ;
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}else if($scope.waitList.modifierSort === 'sorting_asc'){
				$scope.waitList.modifierSort = "sorting_desc";
				$scope.homeWaitListConfig.sort = "-id";
				getHomeWaitList()
			}else if($scope.waitList.modifierSort === 'sorting_desc'){
				$scope.waitList.modifierSort = "sorting_asc";
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}
		};
		var changeHomeWaitAuditorSort = function (waitList)  {
			//清除其他header样式
			$scope.waitList.processSort = "";
			$scope.waitList.nodeSort = "";
			$scope.waitList.createrSort = "";
			$scope.waitList.modifierSort = "";

			if(!!!$scope.waitList.auditorSort){
				$scope.waitList.auditorSort = "sorting_asc" ;
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}else if($scope.waitList.auditorSort === 'sorting_asc'){
				$scope.waitList.auditorSort = "sorting_desc";
				$scope.homeWaitListConfig.sort = "-id";
				getHomeWaitList()
			}else if($scope.waitList.auditorSort === 'sorting_desc'){
				$scope.waitList.auditorSort = "sorting_asc";
				$scope.homeWaitListConfig.sort = "id";
				getHomeWaitList()
			}
		};*/

		var bindListener = function() {

			//流程列表排序/待执行
			/*$scope.changeHomeWaitProcessSort = changeHomeWaitProcessSort;
			$scope.changeHomeWaitNodeSort = changeHomeWaitNodeSort;
			$scope.changeHomeWaitCreaterSort = changeHomeWaitCreaterSort;
			$scope.changeHomeWaitModifierSort = changeHomeWaitModifierSort;
			$scope.changeHomeWaitAuditorSort = changeHomeWaitAuditorSort;*/

			$scope.toManagerProcess = toManagerProcess
		};

		var initPlugins = function() {

			//执行(分页)的配置
			$scope.homeWaitListConfig = homeWaitListConfig;

			//今日待执行
			getHomeWaitList = function () {
				HomeServ.getWaitRun(homeWaitListConfig)
					.then(function(data) {
						if(data.status === 200){
							$scope.waitRun = data;
							$scope.waitRun.result = $scope.waitRun.results.data;
							$scope.$broadcast("toList",{
								waitRun: data.results.data,
								count: data.results.count,
								limit: $scope.homeWaitListConfig.limit,
								page: $scope.homeWaitListConfig.page || data.results.page
							});
						}
					});
			};
			$timeout(function () {
				getHomeWaitList()
			},1000);
			//page指令接受到的数据
			$scope.$on('toPage',function (evt,data) {
				$scope.homeWaitListConfig.page = data.page;
				getHomeWaitList()
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);

/**
 * Created by Administrator on 2017/4/13.
 */
angular.module('HTRD_AutoConsole.A')
	.controller('HomeWarnListCtrl', ['$scope', '$state', '$window','HomeServ','DateParseServ','$timeout',function($scope, $state, $window,HomeServ,DateParseServ,$timeout) {
		console.log('HomeWarnListCtrl');

		//面包屑
	    	var breadcrumbsData = [
		      {
		        'iconClass': 'icon-home',
		        'text': '首页',
		        'link': 'console.base.home.index'
		      },
		      {
		        'text': '执行告警'
		      }
	    	];

		var getHomeWarnList;
		var homeWarnListConfig = {
			page: 1,
			limit: 20,
			sort:'-id',
		};

		var statusMap = {
		    1:{
		      className: "default",
		      text:"检测异常"
		    },
		    2:{
		      className: 'timeout',
		      text:"执行超时"
		    },
		    3:{
		      className: 'error',
		      text:"执行错误"
		    }
		  };

		var changeHomeWarnProcessSort = function(){
			$scope.classState = !!!$scope.classState
			if($scope.classState === true){
				$scope.homeWarnListConfig.sort= 'started_at',
				getHomeWarnList($scope.homeWarnListConfig)

			}else{
				$scope.homeWarnListConfig.sort= '-started_at',
				getHomeWarnList($scope.homeWarnListConfig)
			}
		}


		var bindListener = function() {
			$scope.changeHomeWarnProcessSort = changeHomeWarnProcessSort
		};

		var initPlugins = function() {
			$scope.breadcrumbsData = breadcrumbsData;
			//执行(分页)的配置
			$scope.homeWarnListConfig = homeWarnListConfig;
			$scope.classState = false;

			//执行告警
			getHomeWarnList = function (homeWarnListConfig) {
				HomeServ.getWarnRun(homeWarnListConfig)
					.then(function(data) {

						if(data.status === 200){
							$scope.warnRun = data;
							$scope.warnRun.result = $scope.warnRun.results.data;

							$scope.warnRun.result .map(function(item) {
								var model = statusMap[item.level];
								var started_at = DateParseServ.dateParse(item.started_at);
								item.color = model.className;
						            	item.level = model.text;
								item.started_at = started_at;
						          });

							$scope.$broadcast("toList",{
								list: data.results.data,
								count: data.results.count,
								limit: $scope.homeWarnListConfig.limit,
								page: $scope.homeWarnListConfig.page || data.results.page
							})
						}
					});
			};
			$timeout(function () {
				getHomeWarnList()

			},1000);
			$scope.$on('toPage',function (evt,data) {
				$scope.homeWarnListConfig.page = data.page;
				getHomeWarnList($scope.homeWarnListConfig)
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);

angular.module('HTRD_AutoConsole.A').controller('OperationLogCtrl', ['$scope', '$state', '$window', 'OperationLogServ', function ($scope, $state, $window, OperationLogServ) {

  //面包屑
  var breadcrumbsData = [
    {
      'iconClass': 'icon-info',
      'text': '用户操作日志',
      'link': 'console.base.log'
    }
  ];

  var bindListener = function () {

  };

  var initPlugins = function () {
    $scope.query = '';
    $scope.fromDate = '';
    $scope.untilDate = '';
    $scope.breadcrumbsData = breadcrumbsData;
    $scope.operatorOptions = [
      {
        title: '全部',
        id: 0
      }
    ];
    $scope.operatorSelected = $scope.operatorOptions[0].title;

    OperationLogServ.getLog()
      .then(function(result) {
        if (result.stateCode === 200) {
          $scope.logList = result.data.list;
        }
      });
    OperationLogServ.getUser()
      .then(function(result) {
        if (result.stateCode === 200) {
          $scope.operatorOptions = $scope.operatorOptions.concat(result.data.list);
          $scope.operatorSelected = $scope.operatorOptions[0].title;
        }
      });
  };

  var init = function () {
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('ManagerControlListCtrl', ['$scope', '$state', '$window', '$timeout', 'ManagerControlServ', 'ManagerHolidayServ', 'ManagerListServ', 'AlertServ', 'DialogServ',
    function ($scope, $state, $window, $timeout, ManagerControlServ, ManagerHolidayServ, ManagerListServ, AlertServ, DialogServ) {
        var starpAside, starpModal;

        //选择流程
        var activeProcess = function (item) {
          console.log('activeProcess', item)
          $scope.controlModel.pipeline = item.id;
          $scope.controlModel.pipelineName = item.name;
        };

        var getProcessListByName = function (item) {
          ManagerListServ.getProcessList({
            search: item
          })
          .then(function (ret) {

            if (ret.status === 200) {
              $scope.$broadcast('changeSelectFilterList', {
                data: ret.results.data,
                id: 'controlInfoSelectId'
              });
            };
          });
        };

        var getProcessListByName1 = function (item) {
          $scope.searchControlListText = item;
          ManagerListServ.getProcessList({
              search: item
          })
          .then(function (ret) {

            if (ret.status === 200) {
              $scope.$broadcast('changeSelectFilterList', {
                  data: ret.results.data,
                  id: 'controlListSelectId'
              });
            };
          });
        };

        var switchActive = function (item) {
          $scope.controlModel.isOpen = item;
        };

        // 拼接配置结果文字

        var joinConfigText = function (data) {
            $scope.data = data;

            if ($scope.data['dateMin'] && $scope.data['dateHour'] && $scope.data['dayAndMonth'] && $scope.data['dayAndWeek'] && $scope.data['month']) {
                var nextMin = $scope.data.dateMin.text;
                var nextHour = $scope.data['dateHour']['text'];
                var nextDay = $scope.data['dayAndMonth']['text'];
                var nextWeek = $scope.data['dayAndWeek']['text'];
                var nextMonth = $scope.data['month']['text'];

                var reg = /^[\*]/;
                var newReg = /[\/]/;
                //var work = $scope.data.isExec? ($scope.controlModel.holidayYear?$scope.controlModel.holidayYear: '2017年') + '年执行时间' : ' ';
                var work = $scope.data.isExec? ($scope.controlModel.holidayYear?$scope.controlModel.holidayYear+'年': '  '): ' ';

                 var showWorkTime = '';
                 if ($scope.data.execCycleMap[1] && $scope.data.execCycleMap[2] ) {
                     showWorkTime = ' 全年 ';
                 } else if ($scope.data.execCycleMap[1]){
                     showWorkTime=' 工作日 ';
                 } else if ($scope.data.execCycleMap[2]){
                     showWorkTime=' 节假日 ';
                 }

                if (reg.test(nextMin) || reg.test(nextHour) || reg.test(nextDay) || reg.test(nextWeek) || reg.test(nextMonth) || newReg.test(nextMin) || newReg.test(nextHour) || newReg.test(nextDay)  || newReg.test(nextWeek) || newReg.test(nextMonth)) {
                  var tempNextMin = nextMin.replace(reg, '每').replace(newReg, '分钟每');
                  var tempNextHour = nextHour.replace(reg, '每').replace(newReg, '小时每');
                  var tempNextDay = nextDay.replace(reg, '每').replace(newReg, '日每');

                  var tempNextWeek = nextWeek.replace(reg, '').replace(newReg, '每');

                  var tempNextMonth = nextMonth.replace(reg, '每').replace(newReg, '月每');

                  // 例如：1-5 / 2  表示：1 - 5月每2个月1-5日每2天和周一 - 周五每2天1：00-5：00每2小时01-05分钟每2分钟
                  var tempNameTime= ($scope.data.isExec?'允许触发执行时间: ': '禁止触发执行时间: ') + ($scope.data.holidayName === '请选择'?' ': $scope.data.holidayName);
                  var temp = tempNextMonth + '月' + tempNextDay + '日'  + '和每周' + tempNextWeek + '的' + tempNextHour + '时' + tempNextMin + '分钟';
                  var tempDelWeek = tempNextMonth + '月' + tempNextDay + '日' + tempNextHour + '时' + tempNextMin + '分钟';

                  $scope.controlModel.text= tempNameTime + showWorkTime  +work+temp;

                  if (nextMin === '*' && nextHour === '*' && nextDay === '*' && nextWeek === '*' && nextMonth === '*'){  //全是 * 的规则
                      $scope.controlModel.text=tempNameTime + showWorkTime + '每分钟'

                  } else if (nextWeek === '*' && nextMonth === '*' && nextHour === '*' && nextDay === '*'){
                      $scope.controlModel.text = tempNameTime+ showWorkTime  + '每小时' +tempNextMin + '分'
                  } else if (nextWeek === '*' && nextMonth === '*' && nextDay === '*'){
                      $scope.controlModel.text = tempNameTime + showWorkTime  + '每天' +tempNextHour + '时' +tempNextMin + '分钟'
                  } else if (nextWeek === '*'){
                      $scope.controlModel.text=tempNameTime+ showWorkTime +tempDelWeek;
                  }
                } else {
                    var tempNameTimeShow= ($scope.data.isExec?'允许触发执行时间: ': '禁止触发执行时间: ');
                    var nextWeekStr = '周';
                    var nextWeekStrMap = {
                      1: '周一',
                      2: '周二',
                      3: '周三',
                      4: '周四',
                      5: '周五',
                      6: '周六',
                      7: '周日'
                    };

                    if (nextWeekStrMap[nextWeek]) {
                      nextWeekStr = nextWeekStrMap[nextWeek];
                    }
                    else if (nextWeek.length === 3) {
                      var nextWeekList = [];
                      var splitType;

                      if (nextWeek.indexOf('-') !== -1) {
                        splitType = '-';
                      }

                      else if (nextWeek.indexOf(',') !== -1) {
                        splitType = ',';
                      }

                      else if (nextWeek.indexOf('-') !== -1) {
                        splitType = '-';
                      }

                      else if (nextWeek.indexOf('，') !== -1) {
                        splitType = '，';
                      };
                      nextWeekList = nextWeek.split(splitType);
                      var nextWeekStrList = nextWeekList.map(function(item) {

                        if (!!nextWeekStrMap[item]) {
                          return nextWeekStrMap[item]
                        };
                      })

                      if (nextWeekStrList.length === 2) {
                        nextWeekStr = nextWeekStrList.join(splitType);
                        // nextWeekStr = [nextWeekStrMap[nextWeekList[0]] , nextWeekStrMap[nextWeekList[1]]].join(splitType);
                      };
                    }

                    console.log('nextWeek', nextWeek);
                    console.log('nextWeekStr', nextWeekStr);
                    var temp = nextMonth + '月' + nextDay + '日' + '和每' + nextWeekStr + nextHour + '时' + nextMin + '分钟';
                    console.log('temp', temp);
                    $scope.controlModel.text = tempNameTimeShow + showWorkTime + work + temp;
                }

            }
        };


        // 选择执行设置
        var toggleExecSetting = function (isExec) {
            $scope.controlModel.isExec = isExec;
        };

        var checkedExecCycle = function (item) {
          $scope.controlModel.execCycleMap = $scope.controlModel.execCycleMap || {};
          $scope.controlModel.execCycleMap[item] = !!!$scope.controlModel.execCycleMap[item];
        };

        var addControlProject = function () {
          $scope.controlModel = {
            name: '',
            isOpen: true,
            isExec: true,
            holidayId: 1,
            holidayName: '',
            execCycleMap: {
                '1': true,
                '2': false
            },
            dateMin: {
                text: '*',
                state: false
            },
            dateHour: {
                text: '*',
                state: false
            },
            dayAndMonth: {
                text: '*',
                state: false
            },
            month: {
                text: '*',
                state: false
            },
            dayAndWeek: {
                text: '*',
                state: false
            }
          };

          starpAside = DialogServ.aside({
              'scope': $scope,
              'backdrop': 'static',
              'title': '创建流程计划',
              'templateUrl': 'view/console/aside/controlAdd.html'
          });

          $timeout(function () {
              $('.aside-body').height($('.aside').height() - 150);
          }, 100);

          $scope.getHolidayList();
        };

        var editControlProject = function (item) {
            $scope.controlId = item.id;
            ManagerControlServ.getManagerControlInfo({
                    id: item.id
                })
                .then(function(ret) {

                    if (ret.status === 200) {
                        var data = ret.results;
                        var execCycleArray = data.exec_type.split(',');
                        var holidayName = '';
                        var holidayYear;

                        $scope.holidayList.map(function(holidayItem) {

                            if (data.holiday === holidayItem.id) {
                                holidayName = holidayItem.name;
                                holidayYear = holidayItem.year;
                            };
                        });

                        $scope.controlModel = {
                            name: data.name ,
                            isOpen: data.status,
                            isExec: data.type,

                            holidayId: data.holiday,
                            holidayName: holidayName || '请选择',
                            holidayYear: holidayYear,

                            pipeline: data.pipeline,
                            pipelineName: data.pipeline_name,

                            execCycleMap: {
                                1: (execCycleArray.indexOf('1') !== -1),
                                2: (execCycleArray.indexOf('2') !== -1)
                            },

                            dateMin: {
                                text: data.minute || '*',
                                state: false
                            },

                            dateHour: {
                                text: data.hour || '*',
                                state: false
                            },

                            dayAndMonth: {
                                text: data.day_of_month || '*',
                                state: false
                            },

                            month: {
                                text: data.month_of_year || '*',
                                state: false
                            },

                            dayAndWeek: {
                                text: data.day_of_week || '*',
                                state: false
                            },

                            text: data.result_info
                        };

                        starpAside = DialogServ.aside({
                            'scope': $scope,
                            'backdrop': 'static',
                            'title': '编辑流程计划',
                            'templateUrl': 'view/console/aside/controlAdd.html'
                        });

                        $timeout(function () {
                            $('.aside-body').height($('.aside').height() - 150);
                        }, 100);
                    }
                    else {
                        console.log('error');
                    }
                });
        };

        var submitAddOrEditControlProject = function () {
          var execTypeList = [];

          for (var key in $scope.controlModel.execCycleMap) {

            if (!!$scope.controlModel.execCycleMap[key]) {
              execTypeList.push(key);
            };
          };

          var param = {
            id: $scope.controlId || null,
            name: $scope.controlModel.name,
            type: $scope.controlModel.isExec,
            status: $scope.controlModel.isOpen,
            exec_type: execTypeList.join(','),

            minute: $scope.controlModel.dateMin.text || '*',
            hour: $scope.controlModel.dateHour.text || '*',
            day_of_week: $scope.controlModel.dayAndWeek.text || '*',
            day_of_month: $scope.controlModel.dayAndMonth.text || '*',
            month_of_year: $scope.controlModel.month.text || '*',
            result_info: $scope.controlModel.text || '',

            holiday: $scope.controlModel.holidayId,
            pipeline: $scope.controlModel.pipeline
          };

          if (!$scope.controlId) {
            if(param.name&&param.pipeline){
                ManagerControlServ.addManagerControlInfo(param)
                    .then(function (ret) {

                        $scope.ret = ret.results;
                        AlertServ.showSuccess('保存成功');
                        $scope.getControlProjectList();
                        starpAside.hide();
                    });
            }else{
                // 不填 弹框
                starpModal = DialogServ.modal({
                    'scope': $scope,
                    'backdrop': 'static',
                    'title': '删除流程计划',
                    'templateUrl': 'view/console/modal/controlListEmpty.html'
                });
                //alert("计划名称 和 选择流程 为必填项!")
            }


          } else {
            ManagerControlServ.editManagerControlInfo(param)
            .then(function (ret) {
              AlertServ.showSuccess('编辑成功');
              $scope.getControlProjectList();
              starpAside.hide();
            })
          }
        };

        var delControlProject = function (item) {
            $scope.controlId = item.id;
            $scope.controlContent = item.title;
            starpModal = DialogServ.modal({
                'scope': $scope,
                'backdrop': 'static',
                'title': '删除流程计划',
                'templateUrl': 'view/console/modal/controlConfirmDelete.html'
            });
        };

        var submitDelControlProject = function () {
            starpModal.hide();
            AlertServ.showSuccess('删除成功');

        };

        var closeControlProjectInfo = function () {
            $scope.controlModel = {};
            starpAside.hide();
        };

        var changeHoliday = function (item) {
            $scope.item = item;
            $scope.controlModel.holidayId = item.id;
            $scope.controlModel.holidayName = item.name;
            $scope.controlModel.holidayYear = item.year;
        };

        var getHolidayList = function () {
          var arg = {
              page: 'false'
          };
          ManagerHolidayServ.getHolidayList(arg)   // ，获取全部数据接口
          .then(function (ret) {

            if (ret.status === 200) {
              $scope.holidayList = ret.results;
            } else {
              $scope.holidayList = [];
            };
          });
        };

        var getControlProjectList = function () {   //首次获取数据,并刷新
            ManagerControlServ.getManagerControlList($scope.pageConfig)
                .then(function (ret) {
                    if (ret.status === 200) {
                        $scope.flowDispathList = ret.results.data;
                        $scope.controlList = $scope.flowDispathList;
                        $scope.pageConfig.page = ret.results.page;
                        $scope.$broadcast('toList', {
                            page: $scope.pageConfig.page,
                            count: ret.results.count
                        });

                    } else {
                        $scope.flowDispathList = [];
                    }
                });

        };

        var getControlInfo = function (data) {
            $scope.controlList.map(function (item) {
                //$scope.newControlList.map(function (item) {
                item.active = false;
            });
            $scope.activeId = data.id;
            data.active = true;
        };


        //搜索功能
        var search = function() {
            $scope.pageConfig.page = 1;
            $scope.searchQuery = $scope.query;

            //$scope.getControlProjectList();
            $scope.getProcessList();
        };

        var getProcessList = function() {
          var params = {
            page: $scope.pageConfig.page
          };

          if (!!$scope.searchControlListText) {
            params.pipeline = $scope.controlModel.pipeline;
          };

          ManagerControlServ.getManagerControlList(params)
          .then(function(res) {

            if (res.status === 200) {
                $scope.controlList = res.results.data;
                $scope.pageConfig.page = res.results.page;
                $scope.$broadcast('toList', {
                    page: $scope.pageConfig.page,
                    count: res.results.count
                });
            } else{
                $scope.controlList=[];
            }
          });
        };




        //==========获取手动添加数据
        var getConfigStr = function () {
            $scope.newProjectName = $scope.controlModel.name;
        };


        var bindListener = function () {
            //弹框
           // $scope.changeDateCycle=changeDateCycle;
           // $scope.canceleMode=canceleMode;

            //搜索功能<-
            $scope.search = search;
            $scope.getProcessList = getProcessList;
            //搜索功能 ->

            $scope.switchActive = switchActive;
            $scope.toggleExecSetting = toggleExecSetting;
            $scope.checkedExecCycle = checkedExecCycle;
            $scope.addControlProject = addControlProject;
            $scope.delControlProject = delControlProject;
            $scope.getControlProjectList = getControlProjectList;
            $scope.getControlInfo = getControlInfo;
            $scope.changeHoliday = changeHoliday;
            $scope.submitAddOrEditControlProject = submitAddOrEditControlProject;
            $scope.editControlProject = editControlProject;
            $scope.getHolidayList = getHolidayList;
            $scope.joinConfigText = joinConfigText;
            $scope.closeControlProjectInfo = closeControlProjectInfo;
            $scope.submitDelControlProject = submitDelControlProject;
            $scope.getProcessListByName = getProcessListByName;
            $scope.getProcessListByName1 = getProcessListByName1;

            $scope.activeProcess = activeProcess;
            //======
            $scope.getConfigStr = getConfigStr;
            // $scope.changeText=changeText;
        };

        var initPlugins = function () {
            //搜索功能
            $scope.pageConfig = {
                page: 1
            };


            // 创建流程计划表单数据
            $scope.controlModel = {};

            // 面包屑
            $scope.crumbsConfig = {
                index: {
                    title: '流程调度',
                    icon: 'htrd-icon-control-sm'
                }
            };

            $scope.helpTextMap = {
                'dateMin': {
                    title: '分钟',
                    data: [
                        {
                            title: '0 - 59',
                            text: '允许值是0到59之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如: *表示每分钟'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：0,30表示0和30分钟'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：0-5表示0,1,2,3,4,5分钟'
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如: 0-30/2表示0-30分钟之间每2分钟'
                        }
                    ]
                },

                'dateHour': {
                    title: '小时',
                    data: [
                        {
                            title: '0 - 23',
                            text: '允许值是0到23之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如: *表示每小时'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：0,12表示0和12小时'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：19-23表示19,20,21,22,23小时 '
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：0-20/2表示0-20小时之间每2小时'
                        }
                    ]
                },

                'dayAndMonth': {
                    title: '日',
                    data: [
                        {
                            title: '0 - 31',
                            text: '允许值是1到31之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如：*表示本月每一天'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：1,15表示本月1日和15日'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：1-5表示本月1,2,3,4,5日'
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：1-20/2表示1-20日之间每2天 '
                        }
                    ]
                },

                'month': {
                    title: '月',
                    data: [
                        {
                            title: '0 - 12',
                            text: '允许值是1到12之间的任何整数'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。例如：*表示每月'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：1,6表示1月和6月'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：1-3表示1月,2月,3月'
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：1-5/2表示周一-周五之间每2天'
                        }
                    ]
                },

                'dayToWeek': {
                    title: '周',
                    data: [
                        {
                            title: '0 - 6',
                            text: '允许值是0到6之间的任何整数,0=周日'
                        },

                        {
                            title: '*',
                            text: '代表所有可能的值。*表示一周中的每一天'
                        },

                        {
                            title: ',',
                            text: '指定几个无规则的数字。例如：1,5表示周一和周五'
                        },

                        {
                            title: '-',
                            text: '表示一个整数范围。例如：1-3表示周一,周二,周三 '
                        },

                        {
                            title: '/',
                            text: '指定时间的间隔频率。例如：1-5/2表示周一-周五之间每2天 '
                        }
                    ]
                }
            };

            var height = $(document).height()-243;
            $('.htrd-control-list-unplanned').css('height',height);

            $scope.getControlProjectList();
            $scope.getHolidayList();

            // 监听表单元素变化
            $scope.$watch('controlModel', function (n, o) {
                $scope.joinConfigText(n);
            }, true);


            $scope.helpToggle = function (item) {
                $scope.controlModel[item] = $scope.controlModel[item] || {};
                $scope.controlModel[item].state = !!!$scope.controlModel[item].state;
            };

            // 点击 input 删除*
            $scope.delText=function(item){
                //console.log($event.target);
                //$event.target.value="";
                $scope.controlModel[item].text=" ";

            }

            // 移除输入框默认值   日期月份不能为0
            $scope.change = function (item) {
              var text=$scope.controlModel[item].text;
              var month=$scope.controlModel['month'].text;
              var dayAndWeek=$scope.controlModel['dayAndWeek'].text;
              var dayAndMonth=$scope.controlModel['dayAndMonth'].text;
              var dateHour=$scope.controlModel['dateHour'].text;
              var dateMin=$scope.controlModel['dateMin'].text;

              var reg = /[^\*\/\-\d\,\，]+/.test( text);
              if (reg){
                $scope.controlModel[item].text = '*'
              };
              if (text == '' || month == '0' || dayAndMonth == '0' || dateMin >=60 || dateMin < 0 || dateHour >=24 || dateHour < 0 || dayAndMonth > 31 || dayAndMonth < 0 || dayAndWeek > 6 || dayAndWeek < 0  || month > 12 || month < 0) {
                   $scope.controlModel[item].text = '*';
              };
              var maxNumReg=/[\/\-]+/.test( text);
              var indexKey=text.indexOf('-');
              var lastKey=text.indexOf('/');
              var prevNum=parseInt(text.slice(0,indexKey));
              var nextNum=parseInt(text.slice(indexKey+1));
              var lastNum=parseInt(text.slice(lastKey+1));
              if (month==text){
                  if (maxNumReg){
                      if ( prevNum>12||prevNum<0||nextNum>12||nextNum<0||lastNum>12||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dayAndWeek==text){
                  if (maxNumReg){
                      if ( prevNum>6||prevNum<0||nextNum>6||nextNum<0||lastNum>6||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dayAndMonth==text){
                  if (maxNumReg){
                      if ( prevNum>31||prevNum<0||nextNum>31||nextNum<0||lastNum>31||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dateHour==text){
                  if (maxNumReg){
                      if ( prevNum>=24||prevNum<0||nextNum>=24||nextNum<0||lastNum>=24||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }
              if (dateMin==text){
                  if (maxNumReg){
                      if ( prevNum>=60||prevNum<0||nextNum>=60||nextNum<0||lastNum>=60||lastNum<0 ){
                          $scope.controlModel[item].text = '*';
                      }
                  }
              }

              // *2* - / ，
              if(/\-$/.test(text) ){
                  $scope.controlModel[item].text = '*';
              }
              if(/^\//.test(text) || /\/$/.test(text) || /\/\//.test(text)){
                  $scope.controlModel[item].text = '*';
              }
              if(/^,/.test(text) || /,$/.test(text) || /,,/.test(text)){
                  $scope.controlModel[item].text = '*';
              }
              if(/^\*/.test(text) || /\*$/.test(text) || /\*\*/.test(text) || /\d\*\d/.test(text)){
                  $scope.controlModel[item].text = '*';
              }


            };

            $scope.controlListSelectId = 'controlListSelectId';
            $scope.controlInfoSelectId = 'controlInfoSelectId';

            $scope.pageConfig = {};

            $scope.$on('toPage', function (evt, data) {
                $scope.pageConfig.page = data.page;
                $scope.getControlProjectList();
            });

            $scope.$on('toDate',function(evt,data){
               // (data + 'data')
            });
        };

        var init = function () {
            bindListener();
            initPlugins();
        };

        init();
    }]);

angular.module('HTRD_AutoConsole.A').controller('ManagerCtrl', ['$scope', '$state', '$window', function ($scope, $state, $window) {
}]);

angular.module('HTRD_AutoConsole.A').controller('ManagerHistoryProcessCtrl', ['$scope', '$state', '$window', '$stateParams', 'ManagerProcessQuneeServ',
function($scope, $state, $window, $stateParams, ManagerProcessQuneeServ) {

  var getManagerProcessQuneeInfo = function() {
    console.log($stateParams);
    ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
      id: $stateParams.processId
    })
    .then(function(ret) {

      if (ret.status === 200) {
        $scope.processName = ret.results.name + ' - 历史执行记录';

        $scope.crumbsConfig = {
          index: {
            title: '流程管理',
            icon: 'icon-home'
          },
          items: [
            {
              title: '流程列表',
              icon: 'fa fa-angle-right',
              url: 'console.base.manager.list'
            },

            {
              title: $scope.processName,
              icon: 'fa fa-angle-right'
            }
          ]
        }
      };
    });
  };

  var bindListener = function() {
    $scope.getManagerProcessQuneeInfo = getManagerProcessQuneeInfo;
  };

  var initPlugins = function() {
    $scope.getManagerProcessQuneeInfo();
  };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('ManagerHolidayInfoCtrl', ['$scope', '$state', '$window', '$timeout', '$stateParams', 'ManagerHolidayServ', 'AlertServ', 'DialogServ',
function($scope, $state, $window, $timeout, $stateParams, ManagerHolidayServ, AlertServ, DialogServ) {
  var starpModal;
  var fullYear;

  var getCalendarDayList = function() {
    ManagerHolidayServ.getHolidayInfo({
      id: $stateParams.id
    })
    .then(function(ret) {
      console.log(ret);


      if (ret.status === 200) {
        $scope.hilidayInfo = ret.results;
        JSON.parse(ret.results.days).map(function(item) {
          console.log(arguments)
          $scope.series[item.month - 1][item.monthToWeek - 1][item.dayToWeek].active = true;
        });
        $scope.hilidayInfo.calendarDayList = JSON.parse($scope.hilidayInfo.days);
        $scope.dateCycleText = ret.results.year;
        console.log('$scope.dateCycleText', $scope.dateCycleText);
      } else {

      };
    });
    // var calendarDayList = [{"text":"12","month":"1","day":"12","monthToWeek":2,"dayToWeek":"4","$$hashKey":"object:298","active":true}];
    // console.log('calendarDayList', calendarDayList);
    //
    // // 读取之前选中的日期
    // calendarDayList.map(function(item) {
    //   $scope.series[item.month - 1][item.monthToWeek - 1][item.dayToWeek].active = true;
    // });
    //
    // $scope.hilidayInfo.calendarDayList = calendarDayList;
  };

  // 获得所选年份的日期列表
  var getDateList = function(year) {
    var start_time = year + '-01-01';
    var end_time = year + '-12-31';
    var bd = new Date(start_time),be = new Date(end_time);
    var bd_time = bd.getTime(), be_time = be.getTime(),time_diff = be_time - bd_time;
    var d_arr = [];

    for(var i = 0; i <= time_diff; i += 86400000){
      var ds = new Date(bd_time+i);
      d_arr.push(year + '-' + (ds.getMonth()+1) + '-' + ds.getDate());
    };
    return d_arr;
  };

  // 计算当前日期在本月份的周数
  var getWeekOfMonth = function(weekStart) {
    var weekStartArr = weekStart.split('-');
    var date = new Date(weekStartArr[0], weekStartArr[1] - 1, weekStartArr[2]); // 注意：JS 中月的取值范围为 0~11
    var weekStart = 0;
    var dayOfWeek = date.getDay();
    var day = date.getDate();
    return Math.ceil((day - dayOfWeek - 1) / 7) + ((dayOfWeek >= weekStart) ? 1 : 0);
  };

  // 获得日期的坐标
  var getDatePosition = function(date) {

    // 第几月
    var month = moment(date).format("M");

    // 今年第几周
    var week = moment(date).format("w");

    // 本月第几天
    var day = moment(date).format("DD");

    // 是本周的星期几
    var dayToWeek = moment(date).format('d')

    // 本月第几周 今年第几周 - ((月份 - 1) * 4);
    var monthToWeek = 0;

    monthToWeek = getWeekOfMonth(date);

    var seriesDay = $scope.series[month - 1][monthToWeek - 1][dayToWeek];
    seriesDay.text = day;
    seriesDay.month = month;
    seriesDay.day = day;
    seriesDay.monthToWeek = monthToWeek;
    seriesDay.dayToWeek = dayToWeek;

    if (dayToWeek === '0' || dayToWeek === '6') {
      seriesDay.holiday = true;
    };
  };

  var submitSwitchYear = function() {
    console.log('submitSwitchYear');
    $scope.hilidayInfo.year = $scope.changeYear;
    $scope.parseCalendar($scope.hilidayInfo.year);
    starpModal.hide();
  };

  var changeDateCycle = function(item) {
    $scope.changeYear = item;
    starpModal = DialogServ.modal({
      'scope': $scope,
      'backdrop': 'static',
      'title': '提示',
      'templateUrl': 'view/console/modal/holidayConfirmSwitchYear.html'
    });
  };

  var parseCalendar = function(year) {
    $scope.series = [];

    var monthList = [];

    // 生成所有月
    for (var m = 0;m < 12;m++) {

      var weekList = [];

      // 生成所有周
      for (var w = 0;w < 6;w++) {

        var dayList = [];
        var maxd = 7;

        if (w === 5) {
          maxd = 2;
        };

        // 生成每周的所有天
        for (var d = 0;d < maxd;d++) {

          // 设置默认值
          var day = {
            text: '-'
          };
          dayList.push(day);
        };

        weekList.push(dayList);
      };

      monthList.push(weekList);
    };

    $scope.series = monthList;

    var dateList = $scope.getDateList(year);
    dateList.map(function(item) {
      getDatePosition(item);
    });
  };

  var toggleDay = function(item) {

    if (!!!item.holiday && item.text !== '-') {
      item.active = !!!item.active;
    };
    console.log(item);
  };


  var addHoliday = function() {
    $scope.hilidayInfo.calendarDayList = [];

    $scope.series.map(function(data) {
      data.map(function(items) {
        items.map(function(item) {
          if (item.active) {
            $scope.hilidayInfo.calendarDayList.push(item);
          };
        });
      })
    });

    $scope.hilidayInfo.days = angular.toJson($scope.hilidayInfo.calendarDayList);
    delete $scope.hilidayInfo.calendarDayList;

    if ($stateParams.id) {
      $scope.hilidayInfo.id = $stateParams.id;
      ManagerHolidayServ.editHolidayInfo($scope.hilidayInfo)
      .then(function(ret) {
        if (ret.status === 200) {
          AlertServ.showSuccess();
          $state.go('console.base.manager.holidayList');
        } else {
          AlertServ.showError(ret.msg);
        };
      });
    } else {
      ManagerHolidayServ.addHolidayInfo($scope.hilidayInfo)
      .then(function(ret) {

        console.log("是创建");
        console.log(ret);

        if (ret.status === 200) {
          AlertServ.showSuccess();
          $state.go('console.base.manager.holidayList');
        } else {
          AlertServ.showError(ret.msg);
        };
      });
    };
  };

  var bindListener = function() {
    $scope.changeDateCycle = changeDateCycle;
    $scope.getDateList = getDateList;
    $scope.getDatePosition = getDatePosition;
    $scope.parseCalendar = parseCalendar;
    $scope.toggleDay = toggleDay;
    $scope.addHoliday = addHoliday;
    $scope.getCalendarDayList = getCalendarDayList;
    $scope.submitSwitchYear = submitSwitchYear;
  };

  var initPlugins = function() {
    $scope.dateCycleText = '2017';
    $scope.dateCycleId = 0;

    $scope.title = !!$stateParams.id ? '编辑假日方案' : '新建假日方案';
    $scope.hilidayInfo = {};
    $scope.dateCycleList = [];

    for (var i = 0;i < 10;i++) {
      $scope.dateCycleList.push(i + 2017);
    };
    console.log('$scope.dateCycleList', $scope.dateCycleList);

    $scope.table = {
      xAxis: [
        {
          index: 0,
          text: '日'
        },

        {
          index: 1,
          text: '一'
        },

        {
          index: 2,
          text: '二'
        },

        {
          index: 3,
          text: '三'
        },

        {
          index: 4,
          text: '四'
        },

        {
          index: 5,
          text: '五'
        },

        {
          index: 6,
          text: '六'
        },

        {
          index: 0,
          text: '日'
        },

        {
          index: 1,
          text: '一'
        },

        {
          index: 2,
          text: '二'
        },

        {
          index: 3,
          text: '三'
        },

        {
          index: 4,
          text: '四'
        },

        {
          index: 5,
          text: '五'
        },

        {
          index: 6,
          text: '六'
        },

        {
          index: 0,
          text: '日'
        },

        {
          index: 1,
          text: '一'
        },

        {
          index: 2,
          text: '二'
        },

        {
          index: 3,
          text: '三'
        },

        {
          index: 4,
          text: '四'
        },

        {
          index: 5,
          text: '五'
        },

        {
          index: 6,
          text: '六'
        },

        {
          index: 0,
          text: '日'
        },

        {
          index: 1,
          text: '一'
        },

        {
          index: 2,
          text: '二'
        },

        {
          index: 3,
          text: '三'
        },

        {
          index: 4,
          text: '四'
        },

        {
          index: 5,
          text: '五'
        },

        {
          index: 6,
          text: '六'
        },

        {
          index: 0,
          text: '日'
        },

        {
          index: 1,
          text: '一'
        },

        {
          index: 2,
          text: '二'
        },

        {
          index: 3,
          text: '三'
        },

        {
          index: 4,
          text: '四'
        },

        {
          index: 5,
          text: '五'
        },

        {
          index: 6,
          text: '六'
        },
        {
          index: 0,
          text: '日'
        },

        {
          index: 1,
          text: '一'
        }
      ],
      yAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    };

    // 面包屑
    $scope.crumbsConfig = {
      index: {
        title: '假日管理',
        icon: 'htrd-icon-holiday-sm'
      },

      items: [
        {
          title: '假日计划',
          icon: 'fa fa-angle-right'
        },

        {
          title: $scope.title,
          icon: 'fa fa-angle-right'
        }
      ]
    };
    fullYear = new Date().getFullYear();
    $scope.hilidayInfo.year = fullYear;
    $scope.dateCycleText = fullYear;

    $scope.parseCalendar(fullYear);

    if ($stateParams.id) {
      $scope.getCalendarDayList();
    };
  };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();

  var arr = ['关机', '重启'];
}]);

angular.module('HTRD_AutoConsole.A').controller('ManagerHolidayListCtrl', ['$scope', '$state', '$window', '$timeout', 'ManagerHolidayServ', 'AlertServ', 'DialogServ',
function($scope, $state, $window, $timeout, ManagerHolidayServ, AlertServ, DialogServ) {
  var starpModal;

  // 获取假日方案列表
  var getHolidayList = function() {
    ManagerHolidayServ.getHolidayList($scope.pageConfig)
    .then(function(ret) {
       console.log(ret);  //获取当前 页面 列表数据

      if (ret.status === 200) {
        $scope.holidayList = ret.results.data;
        $scope.pageConfig.page = ret.results.page;

        $scope.$broadcast("toList", {
          page: $scope.pageConfig.page,
          count: ret.results.count
        });

      } else {
        $scope.holidayList = [];
      };
    });
  };

  // 新建假日方案
  var addHoliday = function() {
    console.log('addHoliday');
    $state.go('console.base.manager.holidayInfo');
  };

  // 编辑假日方案
  var editHoliday = function(item) {
    console.log('editHoliday');
    //console.log(item.id);
    $state.go('console.base.manager.holidayInfo', {
      id: item.id
    });
  };

  // 删除单个假日方案
  var delHoliday = function(item) {
    console.log('delHoliday');
    $scope.holidayId = item.id;
    $scope.holidayContent = item.title;
    starpModal = DialogServ.modal({
      'scope': $scope,
      'backdrop': 'static',
      'title': '删除假日方案',
      'templateUrl': 'view/console/modal/holidayConfirmDelete.html'
    });
  };

  var submitDelHoliday = function() {
    console.log('submitDelHoliday');
    //console.log($scope.holidayId);
    starpModal.hide();
    AlertServ.showSuccess('删除成功');
  };

  var bindListener = function() {
    $scope.getHolidayList = getHolidayList;
    $scope.addHoliday = addHoliday;
    $scope.editHoliday = editHoliday;
    $scope.delHoliday = delHoliday;
    $scope.submitDelHoliday = submitDelHoliday;
  };

  var initPlugins = function() {
    $scope.getHolidayList();

    // 面包屑
    $scope.crumbsConfig = {
      index: {
        title: '假日方案',
        icon: 'htrd-icon-holiday-sm'
      }
    };

    $scope.pageConfig = {};

    $scope.$on('toPage', function(evt, data) {
      $scope.pageConfig.page = data.page;
      $scope.getHolidayList();
    });
  };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();
}]);

/**
 * Created by Administrator on 2017/3/25.
 */
angular.module('HTRD_AutoConsole.A').controller('ManagerListCtrl', ['$scope', '$state', '$window', '$timeout', 'ManagerListServ', 'ManagerProcessTreeServ', 'DateParseServ',function($scope, $state, $window, $timeout, ManagerListServ, ManagerProcessTreeServ,DateParseServ) {
  var status = {
      0:{
        text:"未执行"
      },
      1:{
        text:"正在检测"
      },
      2:{
        text:"执行中"
      }
  };

  var stateReviewerOptions = [
      {
        'title': '全部状态'
      },

      {
        'id': 0,
        'title': '待审核'
      },
      {
        'id': 1,
        'title': '已通过'
      },
      {
        'id': 2,
        'title': '已拒绝'
      }
    ];

  var search = function() {
    $scope.pageConfig.page = 1;
    $scope.searchQuery = $scope.query;
    $scope.searchStatus = $scope.statusId;
    console.log($scope.searchStatus);
    $scope.getProcessList();
  };

  var toManagerEdit = function(item) {
    if(!$scope.isClick){
      return;
    }
    $state.go('console.base.manager.edit',
      { id: item.id});
  };

//创建
  var toManagerCreat = function(){
    $state.go('console.base.manager.edit');
  };

  var toManagerProcess = function($event, id) {
    if ($event.target.nodeName !== 'A') {
      $state.go('console.base.manager.process', {
        id: id
      });
    }
  };

  var toManagerRevirwer = function(item){
    //流程审核
    //$state.go('console.base.manager.audit',{id:item.id})
  }

  var toManagerSchedule = function(item){
    //流程调度
    //$state.go('console.base.manager.control',{id:item.id})
  }
  var clearTreeCache = function() {
    localStorage.removeItem('jstree');
  };

  var treeCallBack = function(data) {
    console.log(data) 
    //$scope.group = data.node.id;  //侧边的 组 ID
    var childs=data.node.children;
    if(childs.length>0){
      var temp=childs.join(",");
      //console.log(temp);
      $scope.group = temp;

    }else{
      $scope.group = data.node.id
    }
    $scope.getProcessList();
  };







//====================

  /*var changeOrder = function(type) {

    if (type === 'ignore') {
      return;
    }
    if (type === $scope.orderType) {
      $scope.isUp = !$scope.isUp;
      $scope.getProcessList();
      return;
    }
    $scope.isUp = true;
    $scope.orderType = type;
    $scope.getProcessList();
  };*/

  var changeIdOrder = function(){
    $scope.classReviewState = '';
    $scope.classCreatState = '';
    $scope.classIdState = !!! $scope.classIdState;
    $scope.classState = $scope.classIdState;
    $scope.getProcessList()
  };

  var changeCreatOrder = function(){
    $scope.classReviewState = '';
    $scope.classIdState = '';

    if($scope.classCreatState){
      $scope.classCreatState = !!!$scope.classCreatState;
    }else {
      $scope.classCreatState = true;
    };
    console.log(1111);
    $scope.orderType =  'created_at';
    $scope.classState = $scope.classCreatState;
    $scope.getProcessList()
  };

  var changeReviewOrder = function(){
    $scope.classCreatState = '';
    $scope.classIdState = '';
    if($scope.classReviewState){
      $scope.classReviewState = !!!$scope.classReviewState;
    }else {
      $scope.classReviewState = true;
    };
    $scope.orderType =  'reviewed_at';
    $scope.classState = $scope.classReviewState;
    $scope.getProcessList();
  }

  var changeState = function(item) {
    //console.log(item)
    $scope.statusId = item.id;
  };

  var changeReviewerState = function(item){
    $scope.reviewerStatus = item.id;
  };

  var getProcessList = function() {
    var params = {
      'page': $scope.pageConfig.page,
      'sort': ($scope.classState ? '' : '-') + $scope.orderType,
      'group': $scope.group,     // [1,2,3].join(',')  // 1,2,3       // 侧边的 组 ID -> 无组 子集ID  2 7 8 9 11 12
      //'group': 8,           // 侧边的 组 ID -> 无组 子集ID  2 7 8 9 11 12
      'lock_on':$scope.searchStatus,  // 流程状态 ID 0-2
      'status':$scope.reviewerStatus  // 审核状态 ID 0-2
    };

    if ($scope.searchQuery) {
      params.search = $scope.searchQuery;
    };

    ManagerListServ.getProcessList(params)
    .then(function(res) {
      console.log("获取流程列表",res);
      if (res.status === 200) {
        $scope.processList = res.results.data;
        $scope.total = res.results.count;

        $scope.processList.map(function(item){

          item.created_at = DateParseServ.dateParse(item.created_at);
          item.reviewed_at = DateParseServ.dateParse(item.reviewed_at);
          if(item.lock_on !== 0 || item.status === 1){
            $scope.isClick = false;
          }else {
            $scope.isClick = true;
          };
          var model = $scope.status[item.lock_on];
          item.lock_on = model.text;
          item.status = $scope.stateParse(item.status);
        })
        // page.html未加载,事件传播无效
        $timeout(function() {
          $scope.$broadcast("toList", {
            //当前第几页
            page: $scope.pageConfig.page,
            //共有多少条
            count: $scope.total
          });
        }, 100);
      }
    });

  };



  var bindListener = function() {
    // 查询流程列表
    $scope.search = search;
    // 跳转到编辑页
    $scope.toManagerEdit = toManagerEdit;
    // 跳转到详情页
    $scope.toManagerProcess = toManagerProcess;
    // 清除tree的localstorage
    $scope.clearTreeCache = clearTreeCache;
    // 递归设置tree
    $scope.setTreeData = ManagerProcessTreeServ.setTreeData;
    // tree点击回调
    $scope.treeCallBack = treeCallBack;
    // 改变排序方式(类型/升降)
    $scope.changeIdOrder = changeIdOrder;
    $scope.changeCreatOrder = changeCreatOrder;
    $scope.changeReviewOrder = changeReviewOrder;
    // 更改下拉状态
    $scope.changeState = changeState;
    $scope.changeReviewerState = changeReviewerState;
    // 获取流程列表
    $scope.getProcessList = getProcessList;
    //创建
    $scope.toManagerCreat = toManagerCreat;
    //跳转审核页
    $scope.toManagerRevirwer = toManagerRevirwer;
    //跳转流程调度
    $scope.toManagerSchedule = toManagerSchedule;

    // 分页跳转,返回选中页码
    $scope.$on('toPage', function(evt, data) {
      $scope.pageConfig.page = data.page;
      $scope.getProcessList();
    });
  };

  var initPlugins = function() {
    $window.isEdit = false;
    $scope.pageConfig = {
      page: 1
    };

    $scope.clearTreeCache();
    //获取树的数据
    ManagerProcessTreeServ.getProcessTree()
    .then(function(result) {
      $scope.treeData = result.results.map($scope.setTreeData);
      console.log('$scope.treeData', $scope.treeData);
    });

    //发送请求获取全部列表数据
    $scope.query = '';
    // 排序类型
    $scope.orderType = 'id';
    // 是否升序
    $scope.classState = false;
    $scope.classIdState = false;
    $scope.classReviewState = '';
    $scope.classCreatState = '';

    // 面包屑数据
    $scope.breadcrumbsData = ManagerListServ.breadcrumbsData;
    // 表格标题列表
    $scope.headList = ManagerListServ.headList;
    // 下拉状态选项列表
    $scope.stateOptions = ManagerListServ.stateOptions;
    console.log($scope.stateOptions);
    // 当前状态
    $scope.stateSelected = '全部状态';
    $scope.reviewerSelected = '全部状态';
    // 状态解析(0 => 未审核)
    $scope.stateParse = ManagerListServ.stateParse;
    // $scope.getProcessList();
    $scope.status = status;
    $scope.isClick = true;
    $scope.stateReviewerOptions = stateReviewerOptions;
  };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();

}]);

 angular.module('HTRD_AutoConsole.A').controller('ManagerProcessCtrl', ['$scope', '$state', '$window', '$stateParams', 'ManagerProcessTreeServ', 'ManagerProcessQuneeServ',
function($scope, $state, $window, $stateParams, ManagerProcessTreeServ, ManagerProcessQuneeServ) {

  var getManagerProcessQuneeInfo = function() {
    ManagerProcessQuneeServ.getManagerProcessQuneeInfo({
      id: $stateParams.id
    })
    .then(function(ret) {
      console.log("ret",ret);    //详情页中获取 跳转前的 group || id

      if (ret.status === 200) {
        $scope.processName = ret.results.name;

        $scope.crumbsConfig = {
          index: {
            title: '流程管理',
            icon: 'htrd-icon-process-sm'
          },
          items: [
            {
              title: '流程列表',
              icon: 'fa fa-angle-right',
              url: 'console.base.manager.list'
            },

            {
              title: $scope.processName,
              icon: 'fa fa-angle-right'
            }
          ]
        }
      };
    });
  };

  var bindListener = function() {
    $scope.getManagerProcessQuneeInfo = getManagerProcessQuneeInfo;
  };

  var initPlugins = function() {
    $scope.getManagerProcessQuneeInfo();
  };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('ManagerProcessEditCtrl',['$scope', '$state', '$stateParams','$window',
function($scope, $state, $stateParams,$window) {

    var crumbsEdit = {
      index: {
            title: '运维管理',
            icon: 'icon-puzzle'
        },
      items: [
        {
          title: '流程列表',
          icon: 'fa fa-angle-right',
          url: 'console.base.manager.list'
        },
        {
          title: '编辑流程',
           icon: 'fa fa-angle-right',
          url: 'console.base.manager.edit'
        }
      ]
    };

    var crumbsCreat= {
      index: {
            title: '运维管理',
            icon: 'icon-puzzle'
        },
      items: [
        {
          title: '流程列表',
          icon: 'fa fa-angle-right',
          url: 'console.base.manager.list'
        },
        {
          title: '创建流程',
          icon: 'fa fa-angle-right',
          url: 'console.base.manager.edit'
        }
      ]
    };

    var crumbsTemplate= {
      index: {
            title: '流程模板',
            icon: 'htrd-icon-template-sm'
        },
      items: [
        {
          title: '编辑流程',
           icon: 'fa fa-angle-right',
          url: 'console.base.manager.edit'
        }
      ]
    };

    // $("body, html").on("click",function(e){
    //   if($(e.target).hasClass("btn htrd-c-button qunee-check edit")){
    //     $scope.processInfoState = !!!$scope.processInfoState;
    //     $scope.$broadcast('qunee.process.edit', {
    //       processInfoState: $scope.processInfoState
    //     });
    //   }else{
    //     $scope.$apply(function(){
    //        $scope.processInfoState = false;
    //        $scope.$broadcast('qunee.process.edit', {
    //          processInfoState: $scope.processInfoState
    //        });
    //     })
    //   }
    // });
    //


  var bindListener = function() {

  };

  var initPlugins = function() {
    $scope.crumbsTemplate = crumbsTemplate;
    $scope.crumbsEdit = crumbsEdit;
    $scope.crumbsCreat = crumbsCreat;
  };

  //判断创建与编辑
    if (!!$stateParams.id) {

      if($stateParams.id == 39 || $stateParams.id == 40 || $stateParams.id == 41){
        $scope.templateShow = true;
        $scope.editShow = $scope.creatShow = false;
      }else{
        $scope.editShow = true;
        $scope.creatShow = $scope.templateShow = false;
      }

    } else {
      $scope.creatShow = true;
      $scope.editShow = $scope.templateShow = false;
    };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('ManagerResultCtrl', ['$scope', '$state', '$window', '$timeout', 'ManagerResultServ', 'StatusMapServ', 'DateParseServ',function($scope, $state, $window, $timeout, ManagerResultServ, StatusMapServ,DateParseServ) {

    var config = {
      page: 1
    };

    //面包屑
     $scope.crumbsConfig = {
          index: {
            title: '流程管理',
            icon: 'htrd-icon-process-sm'
          },
          items: [
            {
              title: '流程结果查询',
              icon: 'fa fa-angle-right',
              url: 'console.base.manager.result'
            }
          ]
    };

    var search = function() {
      if($scope.isClick){
        return;
      }
      $scope.config.page = 1;
      $scope.searchQuery = $scope.query;
      $scope.searchStatus = $scope.statusId;
      $scope.getResultList();
    };

    // 更改结果下拉选项
    var resultCallBack = function(item) {
      console.log('item'+item)
      $scope.statusId = item.id;
    };
    var changeOrder = function(type) {
      if (type === 'ignore') {
        return;
      }
      if (type === $scope.orderType) {
        $scope.isUp = !$scope.isUp;
        $scope.getResultList();
        return;
      }
      $scope.isUp = true;
      $scope.orderType = type;
      $scope.getResultList();
    };

    var toManagerProcess = function(item){
      console.log(item);
      $state.go("console.base.manager.historyProcess",{id: item.id, processId: item.pipeline});
    };


    var getResultList = function() {
      var params = {
        'min_date': $scope.config.min_date,
        'max_date': $scope.config.max_date,
        'page': $scope.config.page,
        'sort': ($scope.isUp ? '' : '-') + $scope.orderType,
        'group': $scope.group
      };

      if ($scope.searchQuery) {
        params.search = $scope.searchQuery;
      }
      if ($scope.searchStatus) {
        params.result_status = $scope.searchStatus;
      }

      ManagerResultServ.getResult(params)
        .then(function(res) {
          if (res.status === 200) {
            $scope.processResult = res.results.data;
            $scope.total = res.results.count;

            console.log($scope.processResult)

            $scope.processResult.map(function(item) {
              //console.log(item.started_at+"---"+item.ended_at)
              var started_at = DateParseServ.dateParse(item.started_at);
              item.started_at = started_at;
              if(item.ended_at){
                var ended_at = DateParseServ.dateParse(item.ended_at);
                item.ended_at = ended_at;
              }
            });

            // page.html未加载,事件传播无效
            $timeout(function() {
              $scope.$broadcast("toList", {
                //当前第几页
                page: $scope.config.page,
                //共有多少条
                count: $scope.total
              });
            }, 100);
          }
        });
    };

    var bindListener = function() {
      // 查询结果列表
      $scope.search = search;
      // 结果选择回调
      $scope.resultCallBack = resultCallBack;
      // 结果状态转换为中文
      $scope.resultParse = StatusMapServ.getStatusData;
      // 改变排序方式(类型/升降)
      $scope.changeOrder = changeOrder;
      // 请求流程结果列表
      $scope.getResultList = getResultList;
      //整行点击跳转
      $scope.toManagerProcess = toManagerProcess;
      // 分页跳转,返回选中页码
      $scope.$on('toPage', function(evt, data) {
        $scope.config.page = data.page;
        $scope.getResultList();
      });

      //监听时间变化
      $scope.$on("showBtn",function(evt,data){
        console.log(data)
          $scope.isClick = data.isClick;
          $scope.config.min_date = data.min_date;
          $scope.config.max_date = data.max_date
        })
    };

    var initPlugins = function() {
      $scope.config = config;
      // 搜索字段
      $scope.query = '';

      //时间
      $scope.$on('toDate',function(evt,data){
        $scope.config.min_date = data.min_date;
        $scope.config.max_date = data.max_date;
      });

      // 表格标题数组
      $scope.headList = ManagerResultServ.headList;
      // 结果筛选
      $scope.resultSelected = '全部结果';
      // 结果分类数组
      $scope.resultOptions = ManagerResultServ.resultOptions;
      // 排序类型
      $scope.orderType = 'started_at';

      // 是否升序
      $scope.isUp = false;
      $scope.isClick = false;

      $timeout(function(){
         $scope.getResultList();
      },1000)

    };

    var init = function() {
      bindListener();
      initPlugins();
    };

    init();
  }]);

angular.module('HTRD_AutoConsole.A').controller('ManagerReviewCtrl', ['$scope', '$state', '$timeout', 'ManagerReviewServ', 'ManagerProcessTreeServ', function($scope, $state, $timeout, ManagerReviewServ, ManagerProcessTreeServ) {

  var pageConfig = {
    limit: 2,
    page: 1
  };

  // tree点击回调
  var treeCallBack = function(data) {
    console.log(data);
  };
  
  // 改变排序方式(类型/升降)
  var changeOrder = function(type) {
    if (type === 'ignore') {
      return;
    }
    if (type === $scope.orderType) {
      $scope.isUp = !$scope.isUp;
      return;
    }
    $scope.isUp = true;
    $scope.orderType = type;
  };
  
  var bindListener = function () {

  };
  
  var initPlugins = function () {
    $scope.pageConfig = pageConfig;
    //发送请求获取全部列表数据
    $scope.query = '';
    // 排序类型
    $scope.orderType = 'name';
    // 是否升序
    $scope.isUp = true;
    // 改变排序方式(类型/升降)
    $scope.changeOrder = changeOrder;
    // 面包屑数据
    $scope.breadcrumbsData = ManagerReviewServ.breadcrumbsData;
    // 表格头
    $scope.headList = ManagerReviewServ.headList;
    // 状态解析
    $scope.stateParse = ManagerReviewServ.stateParse;
    // 递归设置tree
    $scope.setTreeData = ManagerProcessTreeServ.setTreeData;
    // 获取流程tree
    ManagerProcessTreeServ.getProcessTree({
        format: 'json'
      })
      .then(function(result) {
        $scope.treeData = result.results.map($scope.setTreeData);
      });
    // tree选中回调
    $scope.treeCallBack = treeCallBack;
    // 获取审核列表
    ManagerReviewServ.getReviewList({
        format: 'json'
      }).then(function(res) {
        if (res.status === 200) {
          $scope.reviewList = res.results.data;
          $scope.total = res.results.count;
          // page.html未加载,事件传播无效
          $timeout(function() {
            $scope.$broadcast("toList", {
              //每页显示多少
              limit: $scope.pageConfig.limit,
              //当前第几页
              page: $scope.pageConfig.page,
              //共有多少条
              count: $scope.total
            });
          }, 100);
        }
      });
  };

  var init = function () {
    bindListener();
    initPlugins();
  };

  init();

}]);
angular.module('HTRD_AutoConsole.A')
.controller('ManagerTestCtrl', ['$scope', '$state', '$window'
, function($scope, $state, $window) {
  console.log('ManagerTestCtrl');
  $('select').select2();
}]);

angular.module('HTRD_AutoConsole.A')
  .controller('ManagerWarnCtrl', ['$scope', '$state', '$window', 'ManagerWarnServ', 'DateParseServ','$timeout',function ($scope, $state, $window, ManagerWarnServ,DateParseServ,$timeout) {

    var getWarnManager;
    var warnConfig = {
      page: 1
    };

     //面包屑
    $scope.crumbsConfig = {
        index: {
          title: '流程管理',
          icon: 'htrd-icon-process-sm'
        },

        items: [
          {
            title: '流程告警查询',
            icon: 'fa fa-angle-right',
            url: 'console.base.manager.warn'
          }
        ]
    };

    //返回告警级别对应的class
    var statusMap = {
      1:{
        className: "default",
        text:"检测异常"
      },
      2:{
        className: 'error',
        text:"执行超时"
      },
      3:{
        className: 'timeout',
        text:"执行错误"
      }
    };

    var getWarnManager = function(warnConfig){
       /*发送请求获取数据*/
      ManagerWarnServ.getResult(warnConfig)
        .then(function(result) {

          if (result.status === 200) {
            $scope.processResult = result.results.data;

            $scope.processResult.map(function(item) {
              var started_at = DateParseServ.dateParse(item.started_at);
              var ended_at = DateParseServ.dateParse(item.ended_at);
              var model = statusMap[item.level];
              item.started_at = started_at;
              item.ended_at = ended_at;
              item.color = model.className;
              item.level = model.text;
            });

            /*分页*/
            $scope.$broadcast("toList", {
                    //当前第几页
                    page: $scope.warnConfig.page,
                    //共有多少条
                    count: result.results.count
              });
            }
        });
      };

    /*查询*/
    var query = function(){
      if($scope.isClick){
        return;
      }
      warnConfig.search = $scope.search;
      //  console.log('开始时间'+$scope.warnConfig.min_date+'--------'+'结束时间'+$scope.warnConfig.max_date)
      getWarnManager(warnConfig)
    };


    /*时间排序*/
    var changeSort = function(){
      $scope.classState = !!!$scope.classState
        if($scope.classState === true){
          $scope.warnConfig.sort= 'started_at',
          getWarnManager($scope.warnConfig)
        }else{
          $scope.warnConfig.sort= '-started_at',
          getWarnManager($scope.warnConfig)
        }
    };

    var bindListener = function () {
      $scope.query = query;
      $scope.changeSort = changeSort;
    };

    var initPlugins = function () {
      $scope.warnConfig = warnConfig;
      $scope.isClick = false;
      $scope.classState = false;

      //时间
      $scope.$on('toDate',function(evt,data){
        $scope.warnConfig.min_date = data.min_date;
        $scope.warnConfig.max_date = data.max_date;
      });

        /*page.html未加载,事件传播无效*/
        $timeout(function(){
          getWarnManager(warnConfig)
        },100);

       /*分页跳转,返回选中页码*/
        $scope.$on('toPage',function (evt,data) {
          $scope.warnConfig.page = data.page;
          getWarnManager(warnConfig)
        });

        //监听时间变化
        $scope.$on("showBtn",function(evt,data){
          $scope.isClick = data.isClick;
          $scope.warnConfig.min_date = data.min_date;
          $scope.warnConfig.max_date = data.max_date
        })

    };

    var init = function () {
      bindListener();
      initPlugins();
    };

    init();
}])
/*.filter('indexOf', [function() {
  var indexOfFilter = function(objArr, attr, text) {
    objArr = objArr || [];
    return objArr.filter(function(item, index) {
      if (item[attr].indexOf(text) > -1) {
        return true;
      }
    });
  };
  return indexOfFilter;
}])
.filter('ltTime', [function() {
  var ltTimeFilter = function(objArr, attr, number) {
    objArr = objArr || [];
    return objArr.filter(function(item, index) {
      if (!number) {
        return true;
      }
      // 结束日期时间指定为当天最后一毫秒
      // 小于指定范围
      if (item[attr] <= (new Date(number).getTime() + 1000 * 60 * 60 * 24 - 1)) {
        return true;
      }
    });
  };
  return ltTimeFilter;
}])
.filter('gtTime', [function () {
  var gtTimeFilter = function (objArr, attr, number) {
    objArr = objArr || [];
    return objArr.filter(function (item, index) {
      if (!number) {
        return true;
      }
      // 大于指定数值
      if (item[attr] >= new Date(number).getTime()) {
        return true;
      }
    });
  };
  return gtTimeFilter;
}]);*/

angular.module('HTRD_AutoConsole.A')
	.controller('AddUserManageCtrl', ['$scope', '$stateParams', '$state','$window','addUserManagementServ','AlertServ', 'DialogServ','$timeout',  function($scope, $stateParams, $state,$window, addUserManagementServ,AlertServ,DialogServ,$timeout) {

		var create_crumbsConfig = {

			index: {
			          title: '用户权限',
			          icon: 'icon-user'
        			},
			items: [
			  {
			    title: '用户管理',
			    icon: 'fa fa-angle-right',
			    url: 'console.base.permission.user'
			  },

			  {
			    title: '添加用户',
			    icon: 'fa fa-angle-right'
			  }
			]
		  };

		  var edit_crumbsConfig = {
		   	index: {
	          title: '用户权限',
	          icon: 'icon-user'
  			},

				items: [
				  {
				    title: '用户管理',
				    icon: 'fa fa-angle-right',
				    url: 'console.base.permission.user'
				  },

				  {
				    title: '编辑用户',
				    icon: 'fa fa-angle-right'
				  }
				]
		  };

		var user = {};

		//组的全部list
		var getGroupAllList = function(){
			addUserManagementServ.getGroupList()
			.then(function(data) {
				if(data.status === 200){
					$scope.groupList = data.results;
					$scope.queryGroup = [ ];
				}
			});
		};

		//编辑
		var getEditUserInfo = function(config){
			addUserManagementServ.getEditUserInfo(config)
		};

		//保存
		var getSaveUserInfo = function(config){
			console.log(config);
			addUserManagementServ.getSaveUserInfo(config)
		};

		//編輯
		var getEditUserInfo = function(config){
			addUserManagementServ.getSaveUserInfo(config)
		};

		//用戶信息
		var getUserInfo = function(id){
			addUserManagementServ.getUserInfo(id)
			.then(function(data) {

				if (data.status === 200) {
					$scope.user = data.results;
					$scope.queryGroup = $scope.user.groupList;
				};
			});
		};

		//密码验证
		var pswBlur = function(){
			if($scope.user.password){

				if (!!!$scope.pswReg.test(user.password)) {

					$('.password').css('display','block');

				}else{

					$('.password').css('display','none');
				}

			}else{

					$('.password').css('display','none');
			}

		};

		//验证密码
		var confirmPswBlur = function(){

			if($scope.password){
				if($scope.user.password !== $scope.password){
					$('.confirmPassword').css('display','block');
				}else{
					$('.confirmPassword').css('display','none');
				}
			}else{
				$('.confirmPassword').css('display','none');
			}

		};

		//验证邮箱
		var emailBlur = function(){
			if (!!!$scope.emailReg.test(user.email)) {

					$('.email').css('display','block');

				}else{

					$('.email').css('display','none');
				}
		};


		//权限设置
		 var select = function(type){
		 	type === 1 ? $scope.user.is_active = true : $scope.user.is_active = false;
		 };

		 //点击保存
		var save = function(){

			if($scope.pswReg.test(user.password) && $scope.emailReg.test(user.email)){
				AlertServ.showSuccess('保存成功');

				if($stateParams.id){
					getEditUserInfo($scope.user)
				}else{
					getSaveUserInfo($scope.user)
				};
			};
		};

		//点击放弃
		var giveUp = function () {
			strapModal = DialogServ.modal({
				'scope': $scope,
				'templateUrl': 'view/console/modal/giveUpSave.html'
			});
			strapModal.$promise.then(strapModal.show);
		};

		//弹出框的确定按钮
		var confirm = function () {
			strapModal.hide();
			$state.go('console.base.userPermission.addUser');
		};

		//保存并添加
		var saveAdd = function(){
			if(!!$stateParams.id){
				getEditUserInfo($scope.user)
			}else{
				getSaveUserInfo($scope.user)
			};
			$state.go('console.base.userPermission.addUser');
		}

		var bindListener = function() {
			$scope.save = save;
			$scope.giveUp = giveUp;
			$scope.saveAdd =saveAdd;
			$scope.confirm = confirm;
			$scope.select = select;
			$scope.pswBlur = pswBlur;
			$scope.confirmPswBlur = confirmPswBlur;
			$scope.emailBlur = emailBlur;
		};

		var initPlugins = function() {
			$scope.edit_crumbsConfig = edit_crumbsConfig;
			$scope.create_crumbsConfig = create_crumbsConfig;
			$scope.title = '选择组';
			$scope.user = user;
			$scope.pswReg = /^[a-zA-Z\d\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\<=>?@\[\]^_`{|}~]{6,20}$/;
			$scope.emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

			//判断添加用户与编辑
			if (!!$stateParams.id) {
				var id = $stateParams.id;
				$scope.isHide = true;
				getGroupAllList();
				getEditUserInfo(id);
			} else {
				getGroupAllList();
			};

			$scope.$on("selectValue",function(evt,data){

				data.selectData = data.selectData.map(function(item){

					if(typeof item === 'object'){
						item =  item.id;
					}
					return item;
				});
				 $scope.user.groupList=data.selectData;
			});
		};

		var init = function() {
			bindListener();
			initPlugins();
		};

		init();

	}]);

/**
 * Created by Administrator on 2017/3/25.
 */
angular.module('HTRD_AutoConsole.A').controller('UserManageCtrl', ['$scope', '$state', '$window',
  'UserManagementServ', 'DateParseServ','DialogServ','AlertServ','$timeout',  function($scope, $state, $window,UserManagementServ,DateParseServ,DialogServ,AlertServ,$timeout) {
  console.log('UserManageCtrl');

  $scope.ctrlScope = $scope;

  var userConfig = {
        page: 1
    };

   var crumbsConfig = {
      index: {
            title: '用户权限',
            icon: 'icon-user'
        },
      items: [
        {
          title: '用户管理',
          icon: 'fa fa-angle-right',
          url: 'console.base.permission.user'
        },
      ]
    };

    var getUserList = function(userConfig){

      UserManagementServ.getUserManagement(userConfig)
          .then(function(data) {
              if(data.status === 200){
                  $scope.userList = data.results.data;
                  $scope.userList.map(function(item){
                    item.is_active == true ? item.is_active = "启用" : item.is_active = "禁用";
                    item.last_login = DateParseServ.dateParse(item.last_login);
                  });

                  $scope.$broadcast("toList",{
                    count: data.results.count,
                    page: $scope.userConfig.page || data.results.page
                });
             }
          });
     } ;

     var getEditList = function(id){
        UserManagementServ.editUserManagement(id);
     };

    var userCallback = function (item) {
      userConfig.result_status = item.id;
    };

    var query = function(){
      userConfig.search = $scope.search;
      getUserList(userConfig);
      $scope.search = ""
    };

    var toAddUser = function(){
      $state.go('console.base.permission.addUser');
    };

    var edit = function(item){
      $state.go("console.base.permission.addUser", {
        id: item.id
      });
    };

    var changePassward = function(item){
      $scope.id = item.id;
      strapModal = DialogServ.modal({
          'scope': $scope,
          'templateUrl': 'view/console/modal/changePassward.html'
        });
      strapModal.$promise.then(strapModal.show);
    };

    //密码验证
    var pswBlur = function(){
        console.log($scope.ctrlScope.password);
        if(!!!$scope.pswReg.test($scope.ctrlScope.password) || !!!$scope.ctrlScope.password){
          $scope.showPsw = false;
      }else{
          $scope.showPsw = true;
      };
    };

    var confirmPswBlur = function(){
      if($scope.ctrlScope.password !== $scope.ctrlScope.confirmPassword){
          $scope.isShow = true;
      }else{
          $scope.isShow = false;
      }
    };

    var confirm = function () {
      if($scope.pswReg.test($scope.ctrlScope.password) && $scope.ctrlScope.password === $scope.ctrlScope.confirmPassword){
        //发送请求c/users/1/password_change
        var param = {
          id:$scope.id,
          password:$scope.ctrlScope.password,
          passwordConfirm:$scope.ctrlScope.confirmPassword
        };
        UserManagementServ.getChangePassword(param)
          .then(function(data){
            if(data.status === 200){
                strapModal.hide();
                AlertServ.showSuccess('修改密码成功')
            }
          });
      }else{
          strapModal.hide();
          AlertServ.showSuccess('修改密码失败')
      }
    };

    var bindListener = function() {
      $scope.userCallback = userCallback;
      //添加用户
      $scope.toAddUser = toAddUser;
      //查询
      $scope.query = query;
      //编辑
      $scope.edit = edit;
      //点击修改密码弹窗
      $scope.changePassward = changePassward;
      //弹出的确定按钮
      $scope.confirm = confirm;
      //修改密码失去焦点
      $scope.pswBlur = pswBlur;
      //确认密码
      $scope.confirmPswBlur =confirmPswBlur;
    };

    var initPlugins = function() {
      //面包屑
      $scope.crumbsConfig = crumbsConfig;
      //传参
      $scope.userConfig = userConfig;
      //密码验证
      $scope.showPsw = true;
      //确认输入
      $scope.isShow = false;
      $scope.pswReg = /^(?![\d]+$)(?![a-zA-Z]+$)(?![!#$%^&*]+$)[\da-zA-Z_]{6,20}$/;
      //下拉列表默认值
      $scope.userText = "全部状态";
      $scope.search = "";

      //下拉列表的状态
      $scope.listStatus = [
         {
          id: -1,
          title: '全部状态'
        },
        {
          id: 1,
          title: '启用'
        },
        {
          id: 0,
          title: '禁用'
        }
      ] ;

       $timeout(function(){
          getUserList();
       },1000);

       $scope.$on('toPage',function (evt,data) {
          $scope.userConfig.page = data.page;
          getUserList()
        });
    };

    var init = function() {
      bindListener();
      initPlugins();
    };

    init();

}]);

angular.module('HTRD_AutoConsole.A')
.controller('DirectiveCtrl', ['$scope', '$state', '$window', function($scope, $state, $window) {
  console.log('DirectiveCtrl');
}]);

angular.module('HTRD_AutoConsole.A')
.controller('FetcoryCtrl', ['$scope', '$state', '$window','$interval', '$timeout', 'SocketServ',
function($scope, $state, $window ,$interval ,$timeout ,SocketServ) {
  console.log('FetcoryCtrl');
  console.log(SocketServ);

  var bindListener = function() {

  };

  var initPlugins = function() {

    // 测试socket效果
    // SocketServ.initSocket();
    // SocketServ.onMessage(function(result) {
    //
    //   if (!Array.isArray(result)) {
    //     console.log(result);
    //   };
    // });
    //
    // $interval(function() {
    //   SocketServ.sendMessage({
    //     title: 'php世界上最好的语言, 某人世界上最笨的前端..'
    //   });
    // }, 2000);
  };

  var init = function() {
    bindListener();
    initPlugins();
  };

  init();
}]);

angular.module('HTRD_AutoConsole.A').controller('PluginCtrl', ['$scope', '$state', '$window', function($scope, $state, $window) {
  console.log('PluginCtrl');
}]);

angular.module('HTRD_AutoConsole.A')
  .controller('ProcessTemplateCtrl', ['$scope', '$state', '$window', 'ManagerWarnServ', 'DateParseServ','$timeout',function ($scope, $state, $window, ManagerWarnServ,DateParseServ,$timeout) {

     //面包屑
     $scope.crumbsConfig = {
       index: {
         title: '流程模板',
         icon: 'htrd-icon-template-sm'
       }
     };

     $scope.data = [
       {
         id: 40,
         title: '开市流程模板',
         count: 10
       },
       {
         id: 41,
         title: '闭市流程模板',
         count: 10
       },
       {
         id: 39,
         title: '巡检流程模板',
         count: 8
       }
     ];

     var processEdit = function (parma) {
       $state.go('console.base.manager.edit',{
         id: parma.id
       })
     }

    var bindListener = function () {
      $scope.processEdit = processEdit;
    };


    var initPlugins = function () {

    };

    var init = function () {
      bindListener();
      initPlugins();
    };

    init();
}])
